How To Convert List To Map In Java

When we deal with data in Java, programmers prefer a map instead of a list because map reduces redundant data and only a key-value pair is accepted which helps in data fetching.

Hence, whenever we have data in the list format, it becomes necessary to convert it into the map as a key-value pair.

The map can be recognized as a key-value pair whereas the list is recognized only through its indexed value.

In this blog, we will look at different methods for converting lists to maps in Java.

Why Is There A Need To Convert List to Map?

There can be individual reasons for converting list into map in java to store user data according to requirements. Some of the reasons are listed below –

  1. To create a unique key-value pair: A list is a sequential or indexed collection of objects and maps store the data in key-value pairs.
  2. Remove redundancy: The list can accept and store duplicate values, which can give the rise to redundancy. Maps do not allow duplicity of data, hence redundancy will be avoided.
  3. Keep track of the information: Map keeps the track of the information by accessing the key-value pairs. In list tracking of information can not be done.
  4. Easily assessing the data: Maps help access the data just by its unique key, but in a list, data should be searched and accessed.
  5. Helps in array manipulation: Map helps to manipulate the array easily by accessing the key-value pair of the item.

Converting a list into a map can also help in different applications according to the environment. To do the conversion some methods are introduced below.

Different Methods To Convert List To Map

There are four different approaches to converting lists to maps in Java. The concept of loop is applied to put every list item on a map. A detailed explanation is given below with a code explanation and a sample problem. Four approaches are:

  1. Using the object of the list
  2. Using Collectors.toMap() method
  3. Creating MultiMap using Collectors.groupingBy()
  4. Using the put() method

Next, we are deep diving into mentioned approaches by method explanation, sample code, code explanation, sample problem, and its solution, etc for crystal clear understanding.

Approach 1: Convert the list to a map by using the object of the list

In this method, we insert every value of the list into the map through the object method. For this approach, a programmer creates a class for defining key-value pairs and then accessing them through a constructor for creating the object of the list.

Sample code:

// Java program to convert the list into a map using an object of the list

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

// create a list
class Listvalues{

	// srno will act as the Key
	private Integer srno;

	// name will act as a value
	private String name;

	// create a constructor for reference
	public Listvalues(Integer srno, String name)
	{

		// assign the value of srno and name
		this.srno = srno;
		this.name = name;
	}

	// return private variable srno
	public Integer getsrno()
	{
		return srno;
	}

	// return private variable name
	public String getName()
	{
		return name;
	}
}

// creating main class
class Main {

	public static void main(String[] args)
	{
		// create a list
		List<Listvalues> listed = new ArrayList<Listvalues>();

		// add the member to the list
		listed.add(new Listvalues(1, "A"));
		listed.add(new Listvalues(2, "B"));
		listed.add(new Listvalues(3, "C"));

		// create a map with the help of the object method 
           //create an object of Map class
		Map<Integer, String> map = new HashMap<>();

		// put every value list into Map
		for (Listvalues listing : listed) {
			map.put(listing.getsrno(), listing.getName());
		}

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

Output:

Map : {1=A, 2=B, 3=C}

Code explanation:

Import the libraries that we needed to compile the code. Create a list using the object of class Listvalues. Class Listvalues consist of a list structure. Add items to the list. Then create the map. Put every item on the map using predefined syntax – through looping. Then Print the items stored in the map.

Approach 2: Using Collectors.toMap() method convert list in map

List is the type of collectors. The collectors class has the function Collectors.toMap() to convert a list into a map. Collectors.toMap() take data members as parameters and create a hash table to store data. Let us understand with the example of code –

Sample code –

// 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 list
class Learners {

	// userid will act as Key
	private Integer userid;

	// name will act as value
	private String name;

	// create a constructor for reference
	public Learners(Integer userid, String name)
	{

		// assign the value of userid and name
		this.userid = userid;
		this.name = name;
	}

	// return private variable userid
	public Integer getuserid()
	{
		return userid;
	}

	// return private variable name
	public String getName()
	{
		return name;
	}
}

// main class and method
class Main {

	public static void main(String[] args)
	{

		// create a list
		List<Learners> lt = new ArrayList<>();

		// add the member of list
		lt.add(new Learners(1, "A"));
		lt.add(new Learners(2, "B"));
		lt.add(new Learners(3, "C"));

		// create map with the help of Collectors.toMap() method
		LinkedHashMap<Integer, String>
			map = lt.stream().collect(
						Collectors.toMap(
								Learners::getuserid,
								Learners::getName,
								(x, y) -> x + ", " + y,
								LinkedHashMap::new)
);

		// print map
		map.forEach(
			(x, y) -> System.out.println(x + "=" + y));
	}
}

Output :

1=A
2=B
3=C

Code explanation:

  1. Define the class Learners and create user id and name as their private data member.
  2. Create a constructor as a reference to member functions.
  3. Return the respective data members by creating a function.
  4. Create the main method for code execution.
  5. Create a list using the Learner’s class and add items to the list.
  6. Create a map using Collectors.toMap() function to convert a list into map.
  7. Then print the map
  8.  and define data members, and member functions to return the value.
  9. Create a main method for code execution.
  10. Create an empty list and add items to the list.
  11. Create a map using the Collectors.toMap() method.
  12. Then print the map using a foreach loop.

Approach 3: Creating MultiMap using Collectors.groupingBy() to convert list into map

By creating a multimap and using the Collectors.groupingBy() method we can convert the desired list into a map. This approach is a little bit hard to apply as syntax is complex and the hash table used for MultiMap.

Sample code:

// Java program for list convert in map using Collectors.groupingBy() method

import java.util.*;
import java.util.stream.Collectors;

// create a list
class Learners {

	// userid will act as Key
	private Integer userid;

	// name will act as value
	private String name;

	// create a constructor for reference
	public Learners(Integer userid, String name)
	{

		// assign the value of userid and name
		this.userid = userid;
		this.name = name;
	}

	// return private variable userid
	public Integer getuserid()
	{
		return userid;
	}

	// return private variable name
	public String getName()
	{
		return name;
	}
}

// main class and method
class Main {

	
	public static void main(String[] args)
	{

		// create a list
		List<Learners> lt = new ArrayList<Learners>();

		// add the member of list
		lt.add(new Learners(1, "A"));
		lt.add(new Learners(1, "a"));
		lt.add(new Learners(2, "B"));
		lt.add(new Learners(2, "b"));

		// create map with the help of Object (learn) 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(
									Learners::getuserid,
									Collectors
										.mapping(
											Learners::getName,
											Collectors
												.toList())));

		// print the multiMap
		System.out.println("MultiMap = " + multimap);
	}
}

Output :

MultiMap = {1=[A, a], 2=[B, b]}

Code explanation:

  1. Import the libraries and create class Learners.
  2. Define data members and member functions by initializing the constructor.
  3. Create a main method and create an empty list.
  4. Insert items in an empty list.
  5. Create a map using the object of the MultiMap Class function.
  6. Create a MultiMap and store the list in it.
  7. Then print the multimap.

Approach 4: Convert list into map using the put() method

By using the iteration and put() method, all list items can be converted to a map. Data members of the parent class are passed as a parameter in the put() method to iterate all key-value pairs.

Sample code:

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

class Learners {

    // userid is a Key
    Integer userid;

    // name is a value
    String name;

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

    // return the value of userid
    public Integer getuserid() {
        return userid;
    }

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

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

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

        // add the member of list
        lt.add(new Learners(1, "A"));
        lt.add(new Learners(2, "B"));
        lt.add(new Learners(3, "C"));
        lt.add(new Learners(4, "D"));

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

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

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

Output :

Map is  : {1=A, 2=B, 3=C, 4=D}

Code explanation:

  1. Import the libraries and define class Learners.
  2. Define data members and member functions of the class and return their values.
  3. Create the main method and create an empty list.
  4. Then add items to the list.
  5. Create an empty map.
  6. Then create a for loop to iterate the list and add the put method to for loop for the conversion of the list into the map.
  7. Print the map.

Best Approach Out Of Four for Converting List into Map

The put( ) method is the easiest and best approach for how to convert a list to a map in Java. Here are some points to justify the statement.

  1. Less line of code: This method reduces the line of code compared to the other methods. A low line of code will increase the efficiency of the program.
  2. Low execution time: This method takes the lowest time to execute. A decrease in execution time will help to run programs fast.
  3. Simple structure: put() method has a simple syntax, which is easier to implement in the code. This helps programmers to apply the method effectively.
  4. Easy to implement: As this approach has a simple and predefined structure it is easy to implement just by changing the parameters of the method.

The programmer should try all approaches and decide the approach according to his experience and choice.

Sample problems

Sample problem 1:

Write a program that creates a list with items – “GOOGLE”, “MICROSOFT”, “IBM” and converts it into a map using the object of the list. The program should then print out each item in the map.

Solution

  • First we create a class to set key-value pair
  • Then we create a list and store the items accordingly.
  • Then we convert the list into map using the object of the list.
  • Then print the map items.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

// create a list
class Company{

	// id will act as the Key
	private Integer id;

	// name will act as a value
	private String name;

	// create a constructor for reference
	public Company(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;
	}
}

// creating main class
class Main {

	public static void main(String[] args)
	{
		// create a list
		List<Company> listed = new ArrayList<Company>();

		// add the member to list
		listed.add(new Company(1, "GOOGLE"));
		listed.add(new Company(2, "MICROSOFT"));
		listed.add(new Company(3, "IBM"));

		// create a map with the help of the object method 
           		//create an object of Map class
		Map<Integer, String> map = new HashMap<>();

		// put every value list into Map
		for (Company listing : listed) {
			map.put(listing.getid(), listing.getName());
		}

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

Output :

Map : {1=GOOGLE, 2=MICROSOFT, 3=IBM}

Sample problem 2:

How to convert list into map in java using Collector.toMap() method. Write a program that creates a List with items = “MAHINDRA”, “HONDA”, and “TATA” and converts it into a map using the Collector.toMap() method. The program should then print the items to the console.

Solution

  • First we create a class to set key-value pairs in list and map.
  • Then we create a list and store the items according to the sample problem.
  • Then we convert the list into a map using the Collector.toMap() method.
  • Then print the map items.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

// create a list
class Company {

	// id will act as Key
	private Integer id;

	// name will act as value
	private String name;

	// create a constructor for reference
	public Company(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 method
class Main {

	public static void main(String[] args)
	{

		// create a list
		List<Company> lt = new ArrayList<>();

		// add the member of list
		lt.add(new Company(1, "MAHINDRA"));
		lt.add(new Company(2, "HONDA"));
		lt.add(new Company(3, "TATA"));

		// create map with the help of Collectors.toMap() method
		LinkedHashMap<Integer, String>
			map = lt.stream().collect(
						Collectors.toMap(
								Company::getid,
								Company::getName,
								(x, y) -> x + ", " + y,
								LinkedHashMap::new)
);

		// print map
		map.forEach(
			(x, y) -> System.out.println(x + "=" + y));
	}
}

Output –

1=MAHINDRA
2=HONDA
3=TATA

Sample problem 3:

Write a program that creates a list with the items – “HP – PAVILION”, “HONOR – MAGICBOOK” and converts it into a map using the Collectors.groupingBy() method. The program should then print the items to the console.

  • First we create a class to set key-value pairs in a list and map using a constructor.
  • Then we create a list and store the items according to the sample problem.
  • Then we convert the list into a map using the Collectors.groupingBy() method.
  • Then print the map items.
// Java program for list convert in map
// with the help of Collectors.groupingBy() method

import java.util.*;
import java.util.stream.Collectors;

// create a list
class Company {

	// id will act as Key
	private Integer id;

	// name will act as value
	private String name;

	// create a constructor for reference
	public Company(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 method
class Main {

	
	public static void main(String[] args)
	{

		// create a list
		List<Company> lt = new ArrayList<Company>();

		// add the member of list
		lt.add(new Company(1, "HP"));
		lt.add(new Company(1, "PAVILION"));
		lt.add(new Company(2, "HONOR"));
		lt.add(new Company(2, "MAGICBOOK"));

		// create map with the help of
		// Object (learn) 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(
									Company::getid,
									Collectors
										.mapping(
											Company::getName,
											Collectors
												.toList())));

		// print the multiMap
		System.out.println("MultiMap = " + multimap);
	}
}

Output :

MultiMap = {1=[HP, PAVILION], 2=[HONOR, MAGICBOOK]}

Sample problem 4:

How to convert list into map in Java using put() method. Write a program that creates a LIST with the items – “INDIA”, “US”, “CANADA”, and “BRAZIL” and converts it into a MAP using the put() method. The program should then print out each item in the map.

  • First we create a class to set key-value pairs in list and map using a class name Company.
  • Then we create a list and store the items according to the sample problem.
  • Then we convert the list into a map using the put() method.
  • Then print the all map items.
// Program to convert List to Map
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

class Company {

    // id is a Key
    Integer id;

    // name is a value
    String name;

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

    // return the value of id
    public Integer getid() {
        return id;
    }

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

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

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

        // add the member of list
        lt.add(new Company(1, "INDIA"));
        lt.add(new Company(2, "US"));
        lt.add(new Company(3, "CANADA"));
        lt.add(new Company(4, "BRAZIL"));

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

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

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

Output :


Map is  : {1=INDIA, 2=US, 3=CANADA, 4=BRAZIL}

Conclusion

These four approaches answer the question of how to convert a list to map in Java. This can help the developer to use map items (key-value pairs) effectively to retrieve data as per the requirement.

Retrieving data can be a crucial task for the software developer but with the help of a map it becomes easy as the key is unique for all items. Data can be accessed using the key.