javajava-8java-stream

Convert a list of objects to a Map with multiple values per key in Java 8


I have a class like this

ObjectA
id 
type

where id is unique but the type can be duplicate so if I have a list of ObjectA like this

(id, type) = (1, "A") , (2, "B"), (3, "C"), (4, "A")

then I want Map<type, List<id>> where map is

< "A",[1,4],
  "B",[2],
  "C",[3] >

It is working with Java 7 but can't find a way to do it in Java 8. In Java 8 I can create key, value pair but not able to create a list if a type is same.


Solution

  • yourTypes.stream()
             .collect(Collectors.groupingBy(
                   ObjectA::getType,
                   Collectors.mapping(
                        ObjectA::getId, Collectors.toList()
    )))