Search code examples
javajava-streamgroupingcollectors

How to convert List to Map using Java Stream API?


I need to convert List of POJO to Map<Integer, List<MyClass>> where the key is the value from MyClass That is the following code looks like this:

public class MyClass {
    public int id;         // this field value must be key of map.
    public String name;
}

public static void main(String... args) {
    List<MyClass> lst = new ArrayList();
    lst.add(new MyClass(1, "John"));
    lst.add(new MyClass(1, "Peter"));
    lst.add(new MyClass(2, "Sarah"));

    Map<Integer, List<MyClass>> res = lst.collect(..);
}

How can I do this? Can you help me?


Solution

  • You can do that using groupingBy:

    Map<Integer, List<MyClass>> res = lst.stream()
                .collect(Collectors.groupingBy(MyClass::getId));
    

    Aside: Minor correction in the existing code, avoid unchecked assignments using:

    List<MyClass> lst = new ArrayList<>();