Mapping java 8 thread collector List <List> to list

Suppose 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 (the same identifier can 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 I can get Map<Employee, List<Car>(e.g. flat list)?

+4
source share
1 answer

I don’t understand why you use groupingBywhen you are not grouping at all. It seems you need to create Mapwhere the key is in Employeeand the value is Employeecars:

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);

, List, Employee::getCars, List .

+6

Source: https://habr.com/ru/post/1676837/


All Articles