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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read