java 8流收集器映射列表<;列表>;列出

java 8流收集器映射列表<;列表>;列出,java,collections,java-8,java-stream,Java,Collections,Java 8,Java Stream,假设我有一门课: public class Employee{ private int id; private List<Car> cars; //getters , equals and hashcode by id } public class Car { private String name; } 公共类员工{ 私有int-id; 私家车名单; //按id的getter、equals和hashcode } 公车{ 私有字符串名称; } 我有一份员工名单(

假设我有一门课:

public class Employee{

  private int id;
  private List<Car> cars;
//getters , equals and hashcode by id
}

public class Car {
  private String name;

}
公共类员工{
私有int-id;
私家车名单;
//按id的getter、equals和hashcode
}
公车{
私有字符串名称;
}
我有一份员工名单(同一id可能重复):

列出emp=。。
Map resultMap=emps.stream().collect(
Collectors.groupingBy(Function.identity(),
Collectors.mapping(Employee::getCars,Collectors.toList());
这给了我
地图

如何获取
地图我不明白当您根本不进行任何分组时,为什么要使用
groupingBy
。似乎您只需要创建一个
地图,其中
员工的钥匙是
员工的车:

Map<Employee, List<Car> map =
    emps.stream().collect(Collectors.toMap(Function.identity(),Employee::getCars);

请注意,这将对
Employee::getCars
返回的一些原始
列表进行变异,因此您可能希望创建一个新的
列表,而不是将一个列表中的元素添加到另一个列表中。

是的,很抱歉,我没有正确阅读案例。您的解决方案很好。我打算使用平面图将列表转换为f列表到单个列表中,但由于它在toMap收集器中,您的解决方案要好得多。请您再帮我一次好吗?如果在员工类中我们设置了汽车,但我想Map@user1321466在这种情况下,您可以将
Employee::getCars
替换为
e->newarraylist(e.getCars())
Map<Employee, List<Car> map =
    emps.stream().collect(Collectors.toMap(Function.identity(),Employee::getCars);
Map<Employee, List<Car> map =
    emps.stream()
        .collect(Collectors.toMap(Function.identity(),
                                  Employee::getCars,
                                  (v1,v2)-> {v1.addAll(v2); return v1;},
                                  HashMap::new);