简体   繁体   中英

java 8 stream collector mapping List<List> to List

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM