2

I have some classes and I am doing some work in a List<WorkDay> which contains a List<LedgerItem>, I have everything working but one part. Well it works, but not exactly how I would like it to.

public Stream<Map<WorkDay, Set<LedgerItem>>> adjustWorkDays(List<WorkDay> workDays) {        
    return workDays.stream()
            .sorted((d1,d2) -> d1.getCreated().compareTo(d2.getCreated()))
            .map(day -> createGroupByWorkDay(day))/*need it to collect here*/;
}

If you can see the return type is Stream<Map<WorkDay, Set<LedgerItem>>> but I want to map this out of the Stream as Map<WorkDay, Set<LedgerItem>> with a collector but just cannot seem to get Collectors.toMap() syntax to do anything but break.

Like I said, everything works perfectly, so I dont need anything outside of the mapping to work.

Just FYI: createGroupByWorkDay returns Map<WorkDay, Set<LedgerItem>> already but only accepts a single WorkDay as this is a requirement so I cannot change the way this is executed...

thanks in advance

EDIT: So the method that I have createGroupByWorkDay that is not listed here works perfectly as expected, and will never be changed. It returns the correct type of Map<WorkDay, Set<LedgerItem>> but only has a signature for one WorkDay like this createGroupByWorkDay(WorkDay day) to the method in question in the original comment uses that to build individual Maps which are grouped by WorkDay and returns, but there could be N number of those, so the method public Stream<Map<WorkDay, Set<LedgerItem>>> adjustWorkDays(List<WorkDay> workDays) should return all of those Maps collected into one map in the collector. If that makes any sense?

2
  • workDays.stream() .sorted((d1,d2) -> d1.getCreated().compareTo(d2.getCreated())).collect(Collectors.groupingBy(WorkDay::getDay,Collectors.toSet())); Commented Aug 7, 2018 at 4:59
  • I've tried exactly this, and it just doesn't want to work this way, which is why I am so baffled. Commented Aug 7, 2018 at 5:10

1 Answer 1

5

Your question is not clear to me. But I guess you may be asking for something like this?

Map<WorkDay, List<LedgerItem>> result = workDays.stream()
                .collect(Collectors.toMap(Function.identity(), WorkDay::getLedgerItems));

If not please explain your problem statement clearly. This is just a guess.

Here's an update,

Map<WorkDay, List<LedgerItem>> result = workDays.stream()
    .map(d -> createGroupByWorkDay(d))
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Sign up to request clarification or add additional context in comments.

1 Comment

You nailed it, got me exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.