How to convert List to Map in Java [Practical Examples]

Convert List to Map in Java

In Java, List is a child interface of Collection in java.util package whereas Map is an interface of java.util.Map package. The List is an ordered collection of objects whereas the Map represents a mapping between a key and a value. However, List allows the duplicate values but Map does not allow the duplicate values. In order, to convert List to Map, the list must have a identifier that converts into the key in the Map.
The list below shows the approaches to convert List to Map in Java.

  • Using the put() method
  • Using the Collectors.toMap() method
  • Using the Collectors.groupingBy() method

 

Method-1: Using the put() method

In this approach, we will get the elements from the list using for loop. Thereafter, one by one this elements are inserted into Map using put method HashMap class. This is the traditional approach to convert List to Map in Java. Here, we are reading the value from the list and writing it to the Map. This approach is used in JDK version 7 or earlier than that. As Map does not allow the null keys or values, the example executes correctly only if there are no null keys or values present in the list. However, if it encounters any null keys or values, it will throw a NullPointerException.

Advertisement

Example : In this example, we have a Staff object containing the staff id as sid and staff name as name stored as a object in the List. We have to convert this staff list to Map. Here, we are iterating over the list and reading the list element one by one. Thereafter, we are using put() method to write to a Map object.

// Program to convert List to Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

class Staff {

    // sid is a Key
    Integer sid;

    // name is a value
    String name;

    // Initialize with constructor
    public Staff(Integer sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    // return the value of sid
    public Integer getsid() {
        return sid;
    }

    // return the value of name
    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {

        // creating empty list
        List < Staff > lt = new ArrayList < Staff > ();

        // add the member of list
        lt.add(new Staff(101, "John"));
        lt.add(new Staff(102, "Riya"));
        lt.add(new Staff(103, "Sam"));
        lt.add(new Staff(104, "Ram"));

        // Creating an empty Map
        Map < Integer, String > m = new HashMap < > ();

        // put every value list to Map
        for (Staff s: lt) {
            m.put(s.getsid(), s.getName());
        }

        // print map
        System.out.println("Map is  : " + m);
    }
}

Output

Map is  : {101=John, 102=Riya, 103=Sam, 104=Ram}

 

Method-2: Using the Collectors.toMap() method

From Java 8 onwards, we can convert List to Map using the stream() and the Collectors.toMap() methods. The toMap() method will return a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. This is a robust method to convert List to Map in Java.

As Map does not allow the null keys or values, the example executes correctly only if there are no null keys or values present in the list. However, if it encounters any null keys or values, it will throw a NullPointerException. We can also convert List to Map using the lambda expressions instead of method references. The example below shows both usage with the toMap function.

Moreover, it provides the way to handle duplicate keys in the list.

Example : In this example, we have a Staff object containing the staff id as sid and staff name as name stored as a object in the List. We have to convert this staff list to Map. Here, we are using toMap() method of Collectors class.

Advertisement
// Program to convert List to Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

class Staff {

    // sid is a Key
    Integer sid;

    // name is a value
    String name;

    // Initialize with constructor
    public Staff(Integer sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    // return the value of sid
    public Integer getsid() {
        return sid;
    }

    // return the value of name
    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {

        // creating empty list
        List < Staff > lt = new ArrayList < Staff > ();

        // add the member of list
        lt.add(new Staff(101, "John"));
        lt.add(new Staff(102, "Riya"));
        lt.add(new Staff(103, "Sam"));
        lt.add(new Staff(104, "Ram"));

        // Creating an empty Map
        Map < Integer, String > m = new HashMap < > ();

        // Using Collectors.toMap
        m = lt.stream().collect(Collectors.toMap(Staff::getsid, Staff::getName));
        System.out.println("Map is " + m);

        // Using Collectors.toMap     
        m = lt.stream().collect(Collectors.toMap(x -> x.getsid(), x -> x.getName()));
        System.out.println("Map is " + m);
    }
}

Output

Map is {101=John, 102=Riya, 103=Sam, 104=Ram}
Map is {101=John, 102=Riya, 103=Sam, 104=Ram}

 

Method-3: Using the Collectors.groupingBy() method

From Java 8 onwards, we can convert List to Map using the stream() and the Collectors.groupingBy() methods. The groupingBy() method will return a Collector implementing a group by operation on input elements. We can use this function if we have multiple values mapping to the same key. Although, it can allow the null value, but not the null keys.

Example : In this example, we have a Staff object containing the staff id as sid and staff name as name stored as a object in the List. We have to convert this staff list to Map. Here, we are using groupingBy() method of Collectors class in case if we have duplicate keys, they will map all the values with a single key.

// Program to convert List to Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

class Staff {
    // sid is a Key
    Integer sid;
    // name is a value
    String name;

    // Initialize with constructor
    public Staff(Integer sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    // return the value of sid
    public Integer getsid() {
        return sid;
    }

    // return the value of name
    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {

        // creating empty list
        List < Staff > lt = new ArrayList < Staff > ();

        // add the member of list
        lt.add(new Staff(101, "John"));
        lt.add(new Staff(102, "Riya"));
        lt.add(new Staff(103, "Sam"));
        lt.add(new Staff(104, "Ram"));

        // Creating an Map         
        Map < Integer, List < String >> m = lt.stream().collect(Collectors.groupingBy(Staff::getsid, Collectors.mapping(Staff::getName, Collectors.toList())));

        System.out.println("Map is " + m);
    }
}

Output

Map is {101=[John], 102=[Riya], 103=[Sam], 104=[Ram]}

 

Summary

The knowledge of converting the List to Map is very useful while working on real time applications. In many situations, we will need to store the data in the map structure for faster access. In this tutorial, we covered three different approach to convert List to Map in Java. As per the requirement of an application, we can choose an appropriate approach for conversion. We learned in detail about this with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on how to convert List to Map in Java.

 

References

List Interface
Map Interface
Collectors Class

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment