Java 8 – Convert Stream to HashMap

In this article, we will discuss how to convert Stream into a HashMap in Java 1.8 version using Stream API

Stream to HashMap :

Using Collectors.toMap() method, we can convert Stream into a Map. There are 2 variants of Collectors.toMap() method,

  1. Collectors.toMap(keyMapper, valueMapper, mergeFunction)
  2. Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier)

1. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction)

  • First variant of Collectors.toMap() method accepts 3 input-arguments
    1. Key mapper – mapping function to produce keys
    2. Value mapper – mapping function to produce values
    3. Merge Function – this is used to resolve collisions between values associated with the same key
  • Above method helps to convert Stream into Map
  • For converting into HashMap, create HashMap object and pass above obtained Map as constructor-argument
  • Finally, print converted HashMap pairs to console

StreamToMapUsingCollectorsToMap.java

package net.bench.resources.stream.to.hashmap;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToMapUsingCollectorsToMap {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to Map<String, Integer>
		Map<String, Integer> map = nameStream
				.collect(Collectors.toMap(
						Function.identity(), // 1. actual String as KEY
						String::length,  // 2. String length as their VALUE
						(key1, key2) -> key1) // 3. duplicate KEY resolver
						);


		// 2.1 print to console
		System.out.println("1. Stream to Map conversion : \n\n" + map);


		// 3. convert Map to HashMap using inter-conversion constructor
		HashMap<String, Integer> hMap = new HashMap<>(map);


		// 3.1 print to console
		System.out.println("\n\n2. Stream to HashMap conversion : \n\n" + hMap);
	}
}

Output:

1. Stream to Map conversion : 

{Lingaraj=8, Abdul=5, Rajiv=5, Santosh=7, Anbu=4}


2. Stream to HashMap conversion : 

{Abdul=5, Rajiv=5, Lingaraj=8, Santosh=7, Anbu=4}

2. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier)

  • This is the 2nd variant of Collectors.toMap() method which accepts 4 input-arguments
    1. Key mapper – mapping function to produce keys
    2. Value mapper – mapping function to produce values
    3. Merge Function – this is used to resolve collisions between values associated with the same key
    4. Supplier – function which returns a new, empty Map into which the results will be inserted
  • Above method helps to convert Stream into HashMap, LinkedHashMap or TreeMap directly or whichever Supplier we pass as 4th argument
  • In the below example, we are passing HashMap implementation class as method/constructor reference HashMap::new
  • Finally, print converted HashMap pairs to console

StreamToHashMapUsingCollectorsToMap.java

package net.bench.resources.stream.to.hashmap;

import java.util.HashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToHashMapUsingCollectorsToMap {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to HashMap<String, Integer>
		HashMap<String, Integer> hMap = nameStream
				.collect(Collectors.toMap(
						Function.identity(), // 1. actual String as KEY
						String::length,  // 2. String length as their VALUE
						(key1, key2) -> key1, // 3. duplicate KEY resolver
						HashMap::new // 4. implementation-class
						));


		// 2.1 print to console
		System.out.println("Stream to HashMap conversion : \n\n" + hMap);
	}
}

Output:

Stream to HashMap conversion : 

{Lingaraj=8, Abdul=5, Rajiv=5, Santosh=7, Anbu=4}

Related Articles:

References :

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to LinkedHashMap
Java 8 - Convert Stream to TreeSet