我有以下型号:
public class Employee {
Set<Position> positions;
}
public class Position {
Area area;
}
然后在我的控制器中我有一个List<Employee>
,我希望得到一个Map<Area, List<Employee>>
的lambda流操作,这可以了解员工每个职位的区域。
我怎样才能做到这一点?
答案 0 :(得分:1)
您需要获得Employee
和Area
之间的平面关联,这样您就可以将其收集到groupingBy
的地图中。
以下是一种方法:
Map<Area, List<Employeee>> map =
empList.stream()
.flatMap (e-> e.positions
.stream() // a Stream<Position> for a single Employee
.map(p->Collections.singletonMap(e,p.area)
.entrySet ()
.iterator ()
.next ()))
.collect (Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping (Map.Entry::getKey,
Collectors.toList())));