Java8 lambda convert list to map card

Is it possible to convert List<Entry>to Map<Employee, Map<LocalDate, Entry>>with a single lambda expression?

public class Entry {
    Employee employee;
    LocalDate date;
}

So far I have come up with something like this:

entries.stream().collect(Collectors.toMap(Collectors.groupingBy(Entry::getEmployee), Collectors.groupingBy(Entry::getDate), Function.identity()));

But this gives a compilation error:

no suitable method found for 
toMap(java.util.stream.Collector<com.a.Entry,capture#1 of ?,java.util.Map<com.a.Employee,
java.util.List<com.a.Entry>>>‌​,java.util.stream.Co‌​llector<com.a.Entry,‌​capture#2 of ?, 
java.util.Map<java.time.LocalDate,java.util.List<com.a.Entry>>>,
java.util.func‌​tion.Function<java.l‌​ang.Object,java.lang‌​.Object>) 

thank

+4
source share
1 answer

Assuming it Entryhas getters and Employeeoverrides hashCode()and equals():

Map<Employee, Map<LocalDate, Entry>> result = entries.stream()
        .collect(Collectors.groupingBy(Entry::getEmployee,
                Collectors.toMap(Entry::getDate, Function.identity())));

Please note that this will throw an exception if the employee has duplicate dates.

+10
source

Source: https://habr.com/ru/post/1667077/


All Articles