[英]Java8 - How to convert a nested maps to list of nested maps gathered by value of inner map's key
[英]Java8 lambda convert List to Map of Maps
是否可以使用一个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>)
谢谢
假设Entry
有getter, Employee
覆盖hashCode()
和equals()
:
Map<Employee, Map<LocalDate, Entry>> result = entries.stream()
.collect(Collectors.groupingBy(Entry::getEmployee,
Collectors.toMap(Entry::getDate, Function.identity())));
请注意,如果员工有重复日期,这将抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.