Java8 Lambda将List转换为Maps [英] Java8 lambda convert List to Map of Maps
本文介绍了Java8 Lambda将List转换为Maps的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用一个lambda表达式将 List< Entry>
转换为 Map< Employee,Map< LocalDate,Entry>>
?
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()));
但这会导致编译错误:
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
具有吸气剂,并且 Employee
覆盖 hashCode()
和 equals()
:
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.
这篇关于Java8 Lambda将List转换为Maps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文