Java 8流收集器映射List<List>到List

4

假设我有以下这个类:

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>(像一个平面列表)?
1个回答

7
我不明白为什么你要使用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,而不是将一个列表的元素添加到另一个列表中。

是的,抱歉我没有仔细阅读这个案例。你的解决方案很好。我本来想使用flatMap将列表的列表转换为单个列表,但由于它在toMap收集器内部,你的解决方案更好。 - Jeremy Grand
请再帮我一次好吗?如果在Employee类中我们有Set<Car> cars,但我想要得到Map<Employee,List<Car>>怎么办? - user1321466
2
在这种情况下,您可以将 Employee::getCars 替换为 e->new ArrayList<Car>(e.getCars()) - Eran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接