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.Collector<com.a.Entry,capture#2 of ?,
java.util.Map<java.time.LocalDate,java.util.List<com.a.Entry>>>,
java.util.function.Function<java.lang.Object,java.lang.Object>)
Thanks
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With