Java8 lambda将List转换为Maps的Map

时间:2017-01-17 22:58:25

标签: java lambda java-8 java-stream

是否可以使用一个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.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>) 

由于

1 个答案:

答案 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())));

请注意,如果员工的日期重复,这将引发异常。