Collectors toMap() method in Java with Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

Map:{GFG=GeeksForGeeks, Geeks, g=geeks}


My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.