Search code examples
java-8java-streamcollectors

Map Java Stream to Map of Objects with Object as Key


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?


Solution

  • 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));