假设我有这个类:
public class Employee{
private int id;
private List<Car> cars;
//getters , equals and hashcode by id
}
public class Car {
private String name;
}
我有一个员工列表(相同的ID可能会重复(:
List<Employee> emps = ..
Map<Employee, List<List<Car>>> resultMap = emps.stream().collect(
Collectors.groupingBy(Function.identity(),
Collectors.mapping(Employee::getCars, Collectors.toList());
这给了我Map<Employee, List<List<Car>>>
,如何获得Map<Employee, List<Car>
(如平面列表(?
我不明白为什么当你根本没有进行任何分组时使用groupingBy
。似乎您只需要创建一个Map
,其中Employee
中的键和值是Employee
的汽车:
Map<Employee, List<Car> map =
emps.stream().collect(Collectors.toMap(Function.identity(),Employee::getCars);
如果要分组以连接同一Employee
的两个实例,您仍然可以将toMap
与合并函数一起使用:
Map<Employee, List<Car> map =
emps.stream()
.collect(Collectors.toMap(Function.identity(),
Employee::getCars,
(v1,v2)-> {v1.addAll(v2); return v1;},
HashMap::new);
请注意,这将改变 Employee::getCars
返回的一些原始List
,因此您可能希望创建一个新List
,而不是将一个列表的元素添加到另一个列表。