Java Stream Collectors.toUnmodifiableMap

By Arvind Rai, October 04, 2020
On this page we will provide Java Stream Collectors.toUnmodifiableMap example introduced in Java 10.
1. The Collectors.toUnmodifiableMap returns a Collector that accumulates the input elements into an unmodifiable Map. Their keys and values are obtained by applying the specified mapping functions to the input elements.
2. To handle duplicate keys, we need to pass BinaryOperator otherwise it will throw error.

1. toUnmodifiableMap Example

Find the method declaration of Collectors.toUnmodifiableMap from Java doc.
public static <T,K,U> Collector<T,?,Map<K,U>> toUnmodifiableMap(
          Function<? super T, ? extends K> keyMapper,
	  Function<? super T, ? extends U> valueMapper) 
If the mapped keys are duplicates, then IllegalStateException is thrown when the collection operation is performed.
Example1.java
package com.concretepage;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Example1 {
  public static void main(String[] args) {
	Map<Integer, Integer> map1 = Stream.of(10, 15, 20)
		.collect(Collectors.toUnmodifiableMap(i -> i, i -> i * 2)); 
	System.out.println(map1);

	Map<Integer, Integer> map2 = IntStream.range(20,  25).boxed()
		.collect(Collectors.toUnmodifiableMap(i -> i + 2, i -> i * 5));
	System.out.println(map2);
	
	Map<Integer, String> map3 = Arrays.asList(1, 2, 3).stream().map(i -> i * 2)
		.collect(Collectors.toUnmodifiableMap(i -> i * 10, i -> "A" + i));
	System.out.println(map3);	
  }
} 
Output
{20=40, 10=20, 15=30}
{26=120, 25=115, 24=110, 23=105, 22=100}
{20=A2, 60=A6, 40=A4} 
Now suppose there are some duplicate values to set as key.
Map<Integer, Integer> map1 = Stream.of(10, 10, 15, 20)
	.collect(Collectors.toUnmodifiableMap(i -> i, i -> i * 2)); 
It will throw error as following.
java.lang.IllegalStateException: Duplicate key 10 (attempted merging values 20 and 20) 

2. toUnmodifiableMap Example with BinaryOperator

Find the method declaration of Collectors.toUnmodifiableMap from Java doc with BinaryOperator.
public static <T,K,U> Collector<T,?,Map<K,U>> toUnmodifiableMap(
                   Function<? super T,? extends K> keyMapper,
		   Function<? super T,? extends U> valueMapper,
		   BinaryOperator<U> mergeFunction) 
If the mapped keys are duplicates, the value mapping function is applied to each equal element, and then results are merged using the provided mergeFunction.
Find the example.
Example2.java
package com.concretepage;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example2 {
  public static void main(String[] args) {
	Map<Integer, Integer> map1 = Stream.of(10, 10, 15, 20)
		.collect(Collectors.toUnmodifiableMap(i -> i, i -> i * 2, (x, y) -> x + y)); 
	System.out.println(map1);
	
	Map<Integer, String> map2 = Arrays.asList(1, 1, 2, 2, 3).stream().map(i -> i * 2)
		.collect(Collectors.toUnmodifiableMap(i -> i * 10, i -> "A" + i, (x, y) -> x + "-" + y));
	System.out.println(map2);
  }
} 
Output
{20=40, 15=30, 10=40}
{60=A6, 20=A2-A2, 40=A4-A4} 
Find one more example.
Example3.java
package com.concretepage;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example3 {
  public static void main(String[] args) {
    Student s1 = new Student(22, "Mahesh");
    Student s2 = new Student(22, "Suresh");
    Student s3 = new Student(23, "Krishna");
    
    Map<Integer, String> map = Stream.of(s1, s2, s3)
      .collect(Collectors.toUnmodifiableMap(Student::getAge, Student::getName, (x, y) -> x + "-" + y));
    
    System.out.println(map);
  }
}
class Student {
  private Integer age;
  private String name;
  public Student(Integer age, String name){
      this.age=age;
      this.name=name;      
  }
  //Sets and Gets
} 
Output
{22=Mahesh-Suresh, 23=Krishna} 

Reference

Stream Collectors
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us