How to Convert List to Map Using Java 8 with Examples

Learn how to convert List to Map using Java 8 Stream API and Collectors.toMap() with examples, duplicate key handling, sorting, and output.

Why Use Convert List to Map Using Java 8?

  • Collectors.toMap() helps create key-value pairs from list objects.
  • It reduces the amount of manual looping code.
  • The code becomes cleaner, shorter, and more readable.
  • It improves data processing using functional programming features.
  • You can quickly map object fields like id, name, or salary.
  • Duplicate keys can be handled using a merge function.
  • Sorting and collecting data into LinkedHashMap are easier.
  • It is widely used in real-time Java applications and interviews.

Syntax:-  Collectors.toMap(keyMapper, valueMapper)

Code Explanation (Step-by-Step) :-

  • A Department class is created with id, name, and websites fields.
  • A list of Department objects is added.
  • Collectors.toMap() is used to convert list elements into key-value pairs.
  • One example maps department ID to name.
  • Another example maps department ID to websites count .
  • A merge function is used to handle duplicate keys means old value.
  • The stream is sorted by websites in descending order.
  • LinkedHashMap preserves the sorted order in the final map.
				
					import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Department {
	private int id;
	private String name;
	private long websites;

	public Department(int id, String name, long websites) {
		super();
		this.id = id;
		this.name = name;
		this.websites = websites;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getWebsites() {
		return websites;
	}

	public void setWebsites(long websites) {
		this.websites = websites;
	}

	@Override
	public String toString() {
		return "Hosting [id=" + id + ", name=" + name + ", websites=" + websites + "]";
	}
}

public class ListToMap {
	public static void main(String[] args) {
		
		List<Department> listD = new ArrayList<Department>();
		listD.add(new Department(1, "san.com", 12455));
		listD.add(new Department(2, "skjh.com", 598700));
		listD.add(new Department(3, "wesd.com", 123450));
		listD.add(new Department(4, "tyui.com", 20000));
		listD.add(new Department(5, "wesd.com", 110000));
		
		Map<Integer, String> name = listD.stream().collect(Collectors.toMap(Department::getId, Department::getName));
		System.out.println("Get department id with the name :- " + name);
		
		Map<Object, Object> map = listD.stream().collect(Collectors.toMap(x -> x.getId(), s -> s.getWebsites()));
		System.out.println("Using department ID to count websites :- " + map);
		
		Map<String, Long> count = listD.stream().collect(
				Collectors.toMap(Department::getName, Department::getWebsites, (oldValue, newValue) -> oldValue));
		System.out.println("Use duplicate key to count websites :- " + count);
		
		List<Department> list = new ArrayList<>();
		list.add(new Department(1, "lightweb.com", 80000));
		list.add(new Department(2, "testode.com", 90000));
		list.add(new Department(3, "javatechnote.com", 120000));
		list.add(new Department(4, "stud.com", 200000));
		list.add(new Department(5, "learn.com", 1));
		list.add(new Department(6, "xyz.com", 100000));
		
		Map response = list.stream()
				       .sorted(Comparator.comparingLong(Department::getWebsites).reversed())
				       .collect(Collectors.toMap(
				       Department::getName,
				       Department::getWebsites,
					   (oldValue, newValue) -> oldValue,
					   LinkedHashMap::new));
		System.out.println("sorts the department data by websites:- " + response);
	}
}
				
			

Output :-
Get department id with the name :- {1=san.com, 2=skjh.com, 3=wesd.com, 4=tyui.com, 5=wesd.com}
Using department ID to count websites :- {1=12455, 2=598700, 3=123450, 4=20000, 5=110000}
Use duplicate key to count websites :- {tyui.com=20000, wesd.com=123450, san.com=12455, skjh.com=598700}
sorts the department data by websites:- {stud.com=200000, javatechnote.com=120000, xyz.com=100000, testode.com=90000, lightweb.com=80000, learn.com=1}

FAQ:-
1. How do you convert a List to a Map in Java 8?
You can convert a List to a Map in Java 8 using Stream API and Collectors.toMap().
2. What happens if duplicate keys are found in Collectors.toMap()?
If duplicate keys exist, Java throws an exception unless you provide a merge function.
3. Why use LinkedHashMap while collecting stream data?
LinkedHashMap preserves insertion order, which is useful after sorting.
4. Can we sort data before converting List to Map in Java 8?
Yes, you can sort the stream first and then collect it into a LinkedHashMap.
5.What Is Comparator.comparingLong() in Java 8?
Comparator.comparingLong() is used to compare and sort objects based on a long value.