Program to Convert List to Map in Java - GeeksforGeeks

19 Jun, 2019
The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes.
The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.
Example:
Input: List : [1="1", 2="2", 3="3"]
Output: Map : {1=1, 2=2, 3=3}

Input: List : [1="Geeks", 2="for", 3="Geeks"]
Output: Map : {1=Geeks, 2=for, 3=Geeks}

Below are various ways to convert List to Map in Java. For this, it is assumed that each element of the List has an identifier which will be used as a key in the resulting Map.
Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method  import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student>            lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Object (stu) method        // create object of Map class        Map<Integer, String> map = new HashMap<>();          // put every value list to Map        for (Student stu : lt) {            map.put(stu.getId(), stu.getName());        }          // print map        System.out.println("Map  : " + map);    }}Output:Map  : {1=Geeks, 2=For, 3=Geeks}
Using Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert  in map// with the help of Collectors.toMap() method  import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Collectors.toMap() method        LinkedHashMap<Integer, String>            map = lt.stream()                      .collect(                          Collectors                              .toMap(                                  Student::getId,                                  Student::getName,                                  (x, y)                                      -> x + ", " + y,                                  LinkedHashMap::new));          // print map        map.forEach(            (x, y) -> System.out.println(x + "=" + y));    }}Output:1=Geeks
2=For
3=Geeks
Creating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert  in map// with the help of Collectors.groupingBy() method  import java.util.*;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(1, "For"));        lt.add(new Student(2, "Geeks"));        lt.add(new Student(2, "GeeksForGeeks"));          // create map with the help of        // Object (stu) method        // create object of Multi Map class          // create multimap and store the value of list        Map<Integer, List<String> >            multimap = lt                           .stream()                           .collect(                               Collectors                                   .groupingBy(                                       Student::getId,                                       Collectors                                           .mapping(                                               Student::getName,                                               Collectors                                                   .toList())));          // print the multiMap        System.out.println("MultiMap = " + multimap);    }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}

Using by object of list:Approach:Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map// Java program for list convert in map// with the help of Object method  import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student>            lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Object (stu) method        // create object of Map class        Map<Integer, String> map = new HashMap<>();          // put every value list to Map        for (Student stu : lt) {            map.put(stu.getId(), stu.getName());        }          // print map        System.out.println("Map  : " + map);    }}Output:Map  : {1=Geeks, 2=For, 3=Geeks}

Approach:
Get the List to be converted into MapCreate an empty MapIterate through the items in the list and add each of them into the Map.Return the formed Map
Get the List to be converted into Map
Create an empty Map
Iterate through the items in the list and add each of them into the Map.
Return the formed Map
// Java program for list convert in map// with the help of Object method  import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.HashMap;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student>            lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Object (stu) method        // create object of Map class        Map<Integer, String> map = new HashMap<>();          // put every value list to Map        for (Student stu : lt) {            map.put(stu.getId(), stu.getName());        }          // print map        System.out.println("Map  : " + map);    }}
Map  : {1=Geeks, 2=For, 3=Geeks}

Using Collectors.toMap() method: This method includes creation of a list of the student objects, and uses Collectors.toMap() to convert it into a Map.Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert  in map// with the help of Collectors.toMap() method  import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Collectors.toMap() method        LinkedHashMap<Integer, String>            map = lt.stream()                      .collect(                          Collectors                              .toMap(                                  Student::getId,                                  Student::getName,                                  (x, y)                                      -> x + ", " + y,                                  LinkedHashMap::new));          // print map        map.forEach(            (x, y) -> System.out.println(x + "=" + y));    }}Output:1=Geeks
2=For
3=Geeks

Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.toMap() methodCollect the formed Map using stream.collect() methodReturn the formed Map
Get the List to be converted into Map
Convert the List into stream using List.stream() method
Create map with the help of Collectors.toMap() method
Collect the formed Map using stream.collect() method
Return the formed Map
// Java program for list convert  in map// with the help of Collectors.toMap() method  import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(2, "For"));        lt.add(new Student(3, "Geeks"));          // create map with the help of        // Collectors.toMap() method        LinkedHashMap<Integer, String>            map = lt.stream()                      .collect(                          Collectors                              .toMap(                                  Student::getId,                                  Student::getName,                                  (x, y)                                      -> x + ", " + y,                                  LinkedHashMap::new));          // print map        map.forEach(            (x, y) -> System.out.println(x + "=" + y));    }}
1=Geeks
2=For
3=Geeks

Creating MultiMap using Collectors.groupingBy():Approach:Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map// Java program for list convert  in map// with the help of Collectors.groupingBy() method  import java.util.*;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(1, "For"));        lt.add(new Student(2, "Geeks"));        lt.add(new Student(2, "GeeksForGeeks"));          // create map with the help of        // Object (stu) method        // create object of Multi Map class          // create multimap and store the value of list        Map<Integer, List<String> >            multimap = lt                           .stream()                           .collect(                               Collectors                                   .groupingBy(                                       Student::getId,                                       Collectors                                           .mapping(                                               Student::getName,                                               Collectors                                                   .toList())));          // print the multiMap        System.out.println("MultiMap = " + multimap);    }}Output:MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}

Approach:
Get the List to be converted into MapConvert the List into stream using List.stream() methodCreate map with the help of Collectors.groupingBy() methodCollect the formed Map using stream.collect() methodReturn the formed Map
Get the List to be converted into Map
Convert the List into stream using List.stream() method
Create map with the help of Collectors.groupingBy() method
Collect the formed Map using stream.collect() method
Return the formed Map
// Java program for list convert  in map// with the help of Collectors.groupingBy() method  import java.util.*;import java.util.stream.Collectors;  // create a listclass Student {      // id will act as Key    private Integer id;      // name will act as value    private String name;      // create curstuctor for reference    public Student(Integer id, String name)    {          // assign the value of id and name        this.id = id;        this.name = name;    }      // return private variable id    public Integer getId()    {        return id;    }      // return private variable name    public String getName()    {        return name;    }}  // main class and methodpublic class GFG {      // main Driver    public static void main(String[] args)    {          // create a list        List<Student> lt = new ArrayList<Student>();          // add the member of list        lt.add(new Student(1, "Geeks"));        lt.add(new Student(1, "For"));        lt.add(new Student(2, "Geeks"));        lt.add(new Student(2, "GeeksForGeeks"));          // create map with the help of        // Object (stu) method        // create object of Multi Map class          // create multimap and store the value of list        Map<Integer, List<String> >            multimap = lt                           .stream()                           .collect(                               Collectors                                   .groupingBy(                                       Student::getId,                                       Collectors                                           .mapping(                                               Student::getName,                                               Collectors                                                   .toList())));          // print the multiMap        System.out.println("MultiMap = " + multimap);    }}
MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}

nidhi_biet
Java-Collections
java-list
Java-List-Programs
java-map
Java-Map-Programs
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java