prz*_*zem 4 java lambda java-8 java-stream
是否有可能转换List<Entry>为Map<Employee, Map<LocalDate, Entry>>一个lambda表达式?
public class Entry {
Employee employee;
LocalDate date;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我想出了类似的东西:
entries.stream().collect(Collectors.toMap(Collectors.groupingBy(Entry::getEmployee), Collectors.groupingBy(Entry::getDate), Function.identity()));
Run Code Online (Sandbox Code Playgroud)
但这会产生编译错误:
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>)
Run Code Online (Sandbox Code Playgroud)
谢谢
shm*_*sel 10
假设Entry有getter和Employeeoverrides hashCode()并且equals():
Map<Employee, Map<LocalDate, Entry>> result = entries.stream()
.collect(Collectors.groupingBy(Entry::getEmployee,
Collectors.toMap(Entry::getDate, Function.identity())));
Run Code Online (Sandbox Code Playgroud)
请注意,如果员工有重复日期,这将抛出异常.