4

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

1 Answer 1

7

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 Lists returned by Employee::getCars, so you might want to create a new List instead of adding the elements of one list to the other.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, sorry I did not properly read the case. Your solution is fine. I was meaning to use the flatMap to convert the list of lists into a single list but as it is inside the toMap collector, your solution is way better.
Could you please help one more time? what if in Employee class we have Set<Car> cars, but I want to get Map<Employee, List<Car>>
@user1321466 In that case you can replace Employee::getCars with e->new ArrayList<Car>(e.getCars()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.