java 8 stream collector mapping List<List> to List
collections, java, java-8, java-stream
Solution
I don't see why you are using `groupingBy` when you are not doing any grouping at all. It seems all you need is to create a `Map` where the key in a `Employee` and the value is the `Employee`'s cars:
Map<Employee, List<Car> map =
emps.stream().collect(Collectors.toMap(Function.identity(),Employee::getCars);
If you are grouping in order to join two instances of the same `Employee`, you can still use `toMap` with a merge function:
Map<Employee, List<Car> map =
emps.stream()
.collect(Collectors.toMap(Function.identity(),
Employee::getCars,
(v1,v2)-> {v1.addAll(v2); return v1;},
HashMap::new);
Note that this will mutate some of the original `List`s returned by `Employee::getCars`, so you might want to create a new `List` instead of adding the elements of one list to the other.
Problem
Lets say I have this class: ``` public class Employee{ private int id; private List<Car> cars; //getters , equals and hashcode by id } public class Car { private String name; } ``` I have a List of Employees (same id may be duplicated): ``` List<Employee> emps = .. Map<Employee, List<List<Car>>> resultMap = emps.stream().collect( Collectors.groupingBy(Function.identity(), Collectors.mapping(Employee::getCars, Collectors.toList()); ``` This gives me `Map<Employee, List<List<Car>>>`, how can I get a `Map<Employee, List<Car>` (like a flat List)?