是否可以使用一个lambda表达式将List<Entry>
转换为Map<Employee, Map<LocalDate, Entry>>
?
public class Entry {
Employee employee;
LocalDate date;
}
到目前为止,我想出了类似的东西:
entries.stream().collect(Collectors.toMap(Collectors.groupingBy(Entry::getEmployee), Collectors.groupingBy(Entry::getDate), Function.identity()));
但这会产生编译错误:
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>)
由于
答案 0 :(得分:10)
假设Entry
有吸气人而Employee
覆盖hashCode()
和equals()
:
Map<Employee, Map<LocalDate, Entry>> result = entries.stream()
.collect(Collectors.groupingBy(Entry::getEmployee,
Collectors.toMap(Entry::getDate, Function.identity())));
请注意,如果员工的日期重复,这将引发异常。