Open In App

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



Parameters: This method accepts following parameters:

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 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

Parameters: This method accepts following parameters:

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 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

Parameters: This method accepts following parameters:

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 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}

Article Tags :