$show=/label

Java 8 Collectors.toMap() - Collectors to map Examples

SHARE:

A quick guide to toMap() method of Collectors class in java 8. This is used to convert the stream into map instance.

1. Overview

In this tutorial, We'll learn the usage of toMap() method of the Collectors class that is added in the jdk 8.

toMap() method is a static method from Collectors class from java 8 onwards.

Collectors.toMap() method is used to convert the stream of object into the Map as needed with the help 3 overloaded methods.
Java 8 Collectors.toMap() - Collectors to map Examples


2. Collectos.toMap() Syntax


toMap() method syntax from java 8 api.
public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper)

public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                    Function<? super T,? extends U> valueMapper,
                                                    BinaryOperator<U> mergeFunction)
													
public static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper,
                                                                Function<? super T,? extends U> valueMapper,
                                                                BinaryOperator<U> mergeFunction,
                                                                Supplier<M> mapSupplier)


3. Collectors toMap() To Convert List to Map


If we have list of objects such as List of strings and this list has to be converted into the map. In the Map, key is the string and value is its length.

Look at the below code how Collectos.toMap() method can be used to transform List to Map.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectorsToMapExample {

	public static void main(String[] args) {
		List<String> numbersinStringList = new ArrayList<>();

		numbersinStringList.add("One");
		numbersinStringList.add("Two");
		numbersinStringList.add("Three");
		numbersinStringList.add("Four");
		numbersinStringList.add("Five");

		Map<String, Integer> map = numbersinStringList.stream()
				.collect(Collectors.toMap(Function.identity(), String::length));
		System.out.println("List : "+numbersinStringList);
		System.out.println("Map : "+map);

	}

}

Output:
List : [One, Two, Three, Four, Five]
Map : {Five=4, One=3, Four=4, Two=3, Three=5}


4. Collectors toMap To Convert List to Map Using Custom Objects


In the previous section, example is based on the List of Strings. But in the realtime applications, we mostly working with the collection of obejcts. Those objects can be any type of user defined types.

So, to handle custom objects with toMap() method is little tricky.

Let us look at the below program that we are going to add the Employee objects to List first and next converting into a map with key as emp id and value is full emp object.


Employee class
package com.javaprogramto.java8.compare;

import java.util.Objects;

public class Employee {

    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id &&
                age == employee.age &&
                Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                "} \n";
    }
}

toMap() method with Custom objects:
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample2 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		
		Map<Integer, Employee> map = employeeList.stream()
				.collect(Collectors.toMap(Employee::getId, Function.identity()));
		
		
		System.out.println("List : "+employeeList);
		System.out.println("Map : "+map);

	}

}

Output:
List : [Employee{id=1, name='One', age=20} 
, Employee{id=2, name='Two', age=30} 
, Employee{id=3, name='Three', age=40} 
, Employee{id=4, name='Four', age=25} 
, Employee{id=5, name='Give', age=35} 
]
Map : {1=Employee{id=1, name='One', age=20} 
, 2=Employee{id=2, name='Two', age=30} 
, 3=Employee{id=3, name='Three', age=40} 
, 4=Employee{id=4, name='Four', age=25} 
, 5=Employee{id=5, name='Give', age=35} 
}


This program compiles and executes without any errors.

You can see the map is with emp id as key and emp object as value.


5. Collectors toMap To Convert List to Map Using Custom duplicate keys


The above section program works flawlessly when all emp id's are unique. What happens if the list has the same employee instance added twice or more.

Just add the below code to the program and run it.
employeeList.add(new Employee(5, "Give", 35));
employeeList.add(new Employee(5, "Give", 35));
Executin is failed with the error "Exception in thread "main" java.lang.IllegalStateException: Duplicate key 5"


It is clearly saying deplicate key with value 5.

How to handle these type of cases when using stream collectors tomap() method. 
When the same key is added to the HashMap, it does not show up any error. It replaces the exisitng value with the new one for the duplicate key.

To achive these behaviour, we need to use toMap() overloaded method with thrid argument BinaryOperator.

Look at the beloe code.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample3 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		employeeList.add(new Employee(5, "Giver", 36));

		Map<Integer, Employee> map = employeeList.stream()
				.collect(Collectors.toMap(Employee::getId, Function.identity(), (oldVal, newVal) -> newVal));

		System.out.println("List : " + employeeList);
		System.out.println("Map : " + map);

	}

}

Output:
List : [Employee{id=1, name='One', age=20} 
, Employee{id=2, name='Two', age=30} 
, Employee{id=3, name='Three', age=40} 
, Employee{id=4, name='Four', age=25} 
, Employee{id=5, name='Give', age=35} 
, Employee{id=5, name='Giver', age=36} 
]
Map : {1=Employee{id=1, name='One', age=20} 
, 2=Employee{id=2, name='Two', age=30} 
, 3=Employee{id=3, name='Three', age=40} 
, 4=Employee{id=4, name='Four', age=25} 
, 5=Employee{id=5, name='Giver', age=36} 
}

6. Collectors toMap To Other Map Types


As of now we wrote the examples. In all of these returned map is HashMap. That means toMap() method returns HashMap by default.

If we want to convert into the different Map implmentation then we need to use another overloaded method of toMap() with 4th argument Supplier.

Look at the below examples to convert the list into TreeMap and ConcurrentHashMap.

TreeMap is a sorted map by key where as ConcurrentHashMap works in multithreaded enviornments.
package com.javaprogramto.java8.collectors.tomap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.javaprogramto.java8.compare.Employee;

public class CollectorsToMapExample4 {

	public static void main(String[] args) {
		List<Employee> employeeList = new ArrayList<>();

		employeeList.add(new Employee(1, "One", 20));
		employeeList.add(new Employee(2, "Two", 30));
		employeeList.add(new Employee(3, "Three", 40));
		employeeList.add(new Employee(4, "Four", 25));
		employeeList.add(new Employee(5, "Give", 35));
		employeeList.add(new Employee(5, "Giver", 36));

		// TreeMap example
		// converting duplicate keys into the TreeMap
		Map<Integer, Employee> treeMap = employeeList.stream().collect(
				Collectors.toMap(Employee::getId, Function.identity(), (oldVal, newVal) -> newVal, TreeMap::new));

		System.out.println("ArrayList : " + employeeList);
		System.out.println("TreeMap : " + treeMap);

		// ConcurrentHashMap example
		// converting duplicate keys into the ConcurrentHashMap
		Map<Integer, Employee> concurrentHashMap = employeeList.stream().collect(Collectors.toMap(Employee::getId,
				Function.identity(), (oldVal, newVal) -> newVal, ConcurrentHashMap::new));

		System.out.println("ArrayList : " + employeeList);
		System.out.println("ConcurrentHashMap : " + concurrentHashMap);

	}

}


7. Conclusion


In this article, We've seen how to use Collectors.toMap() method and how to handle the duplicate keys in Map when the source list is with duplicates.

How to convert the stream into TreeMap or any other Map types.





COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Collectors.toMap() - Collectors to map Examples
Java 8 Collectors.toMap() - Collectors to map Examples
A quick guide to toMap() method of Collectors class in java 8. This is used to convert the stream into map instance.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQP0r2AsrVK5VokhoEmAfP5dqxdClzc_BuB5P_VlYBvu__q_8FHjsHmZ05DpLWlCyemHTxRw11XO8yqzpWxrNVXVq4WYZBIoREltwfcJtW7gB9IbSIxyBYiicYNyrULvYTOrvbXkAztgM/w400-h297/Java+8+Collectors.toMap%2528%2529+-+Collectors+to+map+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQP0r2AsrVK5VokhoEmAfP5dqxdClzc_BuB5P_VlYBvu__q_8FHjsHmZ05DpLWlCyemHTxRw11XO8yqzpWxrNVXVq4WYZBIoREltwfcJtW7gB9IbSIxyBYiicYNyrULvYTOrvbXkAztgM/s72-w400-c-h297/Java+8+Collectors.toMap%2528%2529+-+Collectors+to+map+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/11/java-collectors-tomap.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/11/java-collectors-tomap.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content