Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 lambda convert List to Map of Maps

Is it possible to transform List<Entry> to Map<Employee, Map<LocalDate, Entry>> with one lambda expression?

public class Entry {
    Employee employee;
    LocalDate date;
}

So far i have came 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.Ent‌ry>>>,
java.util.func‌​tion.Function<java.l‌​ang.Object,java.lang‌​.Object>) 

Thanks

like image 315
przem Avatar asked Jan 17 '17 22:01

przem


People also ask

Can Map be converted into list using toList?

The output of the program is the same as Example 1. In the above program, instead of using ArrayList constructor, we've used stream() to convert the map to a list. We've converted the keys and values to stream and convert it to a list using collect() method passing Collectors ' toList() as a parameter.


1 Answers

Assuming Entry has getters and Employee overrides hashCode() and equals():

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

Note that this will throw an exception if an employee has duplicate dates.

like image 56
shmosel Avatar answered Oct 30 '22 06:10

shmosel