Collectors toMap() method in Java with Examples
Last Updated :
06 Dec, 2018
The
toMap() method is a static method of
Collectors class which returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. Note that keys are unique and if in any case the keys are duplicated then an IllegalStateException is thrown when the collection operation is performed.
There are 3 overloads of toMap() method:
toMap(Function keyMapper, Function valueMapper)
Syntax:
public static Collector<T, ?, Map>
toMap(Function keyMapper, Function valueMapper)
where
- T: Type of input elements.
- Map: Output Map.
- interface Collector: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.
- toMap(): Static method of Collectors class and return a Collector which collects elements into a Map whose keys and values are the result of applying mapping functions to the input elements. The Collectors class is under the java.util.streams package.
Parameters: This method accepts following parameters:
- keyMapper: a mapping function to produce keys
- valueMapper: a mapping function to produce values
Return Value: This method returns a Collector which collects elements into a Map whose keys and values are the result of applying mapping functions to the input elements
Below example illustrates the above method:
Java
// Java program to demonstrate
// toMap() method with unique keys
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create a String with no repeated keys
Stream<String[]>
str = Stream
.of(new String[][] { { "GFG", "GeeksForGeeks" },
{ "g", "geeks" },
{ "G", "Geeks" } });
// Convert the String to Map
// using toMap() method
Map<String, String>
map = str.collect(
Collectors.toMap(p -> p[0], p -> p[1]));
// Print the returned Map
System.out.println("Map:" + map);
}
}
Output:
Map:{G=Geeks, g=geeks, GFG=GeeksForGeeks}
toMap(Function keyMapper, Function valueMapper, BinaryOperator<U> mergeFunction)
This is an overload of
toMap() method in which an extra parameter is added to the key and values and that is the
merger function. The task of the function is to merge the values having the same key in a way defined by the coder. This overloaded method is recommended only in the case when there are same keys for multiple values. A simple example is given as follows.
Syntax:
public static Collector<T, ?, Map>
toMap(Function keyMapper,
Function valueMapper,
BinaryOperator<U> mergeFunction)
where
- T: Type of input elements.
- Map: Output Map.
- interface Collector: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.
- toMap(): Static method of Collectors class and return a Collector which collects elements into a Map whose keys and values are the result of applying mapping functions to the input elements. The Collectors class is under the java.util.streams package.
Parameters: This method accepts following parameters:
- keyMapper: a mapping function to produce keys
- valueMapper: a mapping function to produce values
- mergeFunction: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
Return Value: This method returns a Collector which collects elements into a Map whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function
Below example illustrates the above method:
Java
// Java program to demonstrate
// toMap() method without unique keys
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create a String with repeated keys
Stream<String[]>
str = Stream
.of(new String[][] { { "GFG", "GeeksForGeeks" },
{ "g", "geeks" },
{ "GFG", "geeksforgeeks" } });
// Get Map from String
// using toMap() method
Map<String, String>
map = str
.collect(Collectors
.toMap(p -> p[0], p -> p[1], (s, a) -> s + ", " + a));
// Print the Map
System.out.println("Map:" + map);
}
}
Output:
Map:{g=geeks, GFG=GeeksForGeeks, geeksforgeeks}
toMap(Function keyMapper, Function valueMapper, BinaryOperator<U> mergeFunction, Supplier mapSupplier)
This is an overloaded method of
toMap() with an additional parameter .i.e Suppliers. We need to pass supplier here. Supplier is the interface of the java.util.Function class. This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. If we want to return LinkedHashMap, we need to pass supplier as LinkedHashMap::new. In the example as follows we will be doing the same.
Syntax:
public static <T, K, U, M extends Map> Collector
toMap(Function keyMapper,
Function valueMapper,
BinaryOperator<U> mergeFunction,
Supplier mapSupplier)
where
- T: Type of input elements.
- Map: Output Map.
- interface Collector: A mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed. Reduction operations can be performed either sequentially or in parallel.
- toMap(): Static method of Collectors class and return a Collector which collects elements into a Map whose keys and values are the result of applying mapping functions to the input elements. The Collectors class is under the java.util.streams package.
Parameters: This method accepts following parameters:
- keyMapper: a mapping function to produce keys
- valueMapper: a mapping function to produce values
- mergeFunction: a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
- mapSupplier : a function which returns a new, empty Map into which the results will be inserted
Return Value: This method returns a Collector which collects elements into a Map whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function
Below example illustrates the above method:
Java
// Java program to demonstrate
// toMap() method
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Create a String to be converted
Stream<String[]>
Ss1 = Stream
.of(new String[][] { { "GFG", "GeeksForGeeks" },
{ "g", "geeks" },
{ "GFG", "Geeks" } });
// Get Map from String
// using toMap() method
LinkedHashMap<String, String>
map2 = Ss1
.collect(Collectors
.toMap(
p -> p[0], p -> p[1], (s, a) -> s + ", " + a, LinkedHashMap::new));
// Print the Map
System.out.println("Map:" + map2);
}
}
Output:
Map:{GFG=GeeksForGeeks, Geeks, g=geeks}
Similar Reads
Collectors toList() method in Java with Examples
The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method c
2 min read
Collections singletonMap() method in Java with Examples
The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable. Syntax: public static Map singletonMap(K key, V value) Parameters: This method takes the following parameters as a arg
2 min read
Collections min() method in Java with Examples
min(Collection<? extends T> coll) The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements
4 min read
Collections newSetFromMap() method in Java with Examples
The newSetFromMap() method of java.util.Collections class is used to return a set backed by the specified map. The resulting set displays the same ordering, concurrency, and performance characteristics as the backing map. In essence, this factory method provides a Set implementation corresponding to
2 min read
Collectors toSet() in Java with Examples
Collectors toSet() returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. This is an unordered Collector i.e, the collection operation does not commit to preserving the encounter
2 min read
Collections synchronizedMap() method in Java with Examples
The synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map. Syntax: public static <K, V
2 min read
Collections unmodifiableMap() method in Java with Examples
The unmodifiableMap() method of java.util.Collections class is used to return an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to mod
2 min read
Collections max() method in Java with Examples
max(Collection<? extends T> coll) The max() method of java.util.Collections class is used to return the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements
5 min read
Collections list() method in Java with Examples
The list() method of java.util.Collections class is used to return an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that requi
2 min read
Collection add() Method in Java with Examples
The add(E element) of java.util.Collection interface is used to add the element 'element' to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false. Syntax: Collection.add(E element) Paramet
4 min read