Close

Java 8 Streams - Collectors.toUnmodifiableMap() Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.Collectors

java.lang.Objectjava.lang.Objectjava.util.stream.Collectorsjava.util.stream.CollectorsLogicBig

Methods:

public static <T,K,U> Collector<T,?,Map<K,U>> toUnmodifiableMap(Function<? super T,? extends K> keyMapper,
                                                                Function<? super T,? extends U> valueMapper)
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)

Returns a Collector that accumulates the input elements into an unmodifiable map, whose keys and values are the result of applying the provided mapping functions to the input elements..

Type Parameters:
T - the type of the input elements
K - the output type of the key mapping function
U - the output type of the value mapping function
Parameters:
keyMapper - a mapping function to produce keys, must be non-null
valueMapper - a mapping function to produce values, must be non-null
mergeFunction (applicable to second method only) - a merge function, used to resolve collisions between values associated with the same key.
Returns:
a Collector that accumulates the input elements into an unmodifiable Map, whose keys and values are the result of applying the provided mapping functions to the input elements

Since Java 10.



Examples


package com.logicbig.example.collectors;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ToUnmodifiableMapExample {

public static void main(String... args) {
Map<Integer, Double> map =
IntStream.range(1, 5)
.boxed()
.collect(Collectors.toUnmodifiableMap(
i -> i,
i -> Math.pow(i, 3))
);
System.out.println(map);
System.out.println(map.getClass().getTypeName());
}
}

Output

{1=1.0, 2=8.0, 3=27.0, 4=64.0}
java.util.ImmutableCollections$MapN
Original Post




package com.logicbig.example.collectors;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ToUnmodifiableMapExample2 {

public static void main(String... args) {
Map<Integer, List<String>> map =
Stream.of("rover", "joyful", "depth", "hunter")
.collect(Collectors.toUnmodifiableMap(
String::length,
List::of,
ToUnmodifiableMapExample2::mergeFunction)
);
System.out.println(map);
}

private static List<String> mergeFunction(List<String> l1, List<String> l2) {
List<String> list = new ArrayList<>();
list.addAll(l1);
list.addAll(l2);
return list;
}
}

Output

{5=[rover, depth], 6=[joyful, hunter]}
Original Post




See Also