Collectors toMap

Java-Collectors toMap

Collectors toMap

The Collectors class provides a large number of static methods for common collectors. The toMap( ) method of the collectors is used to collect stream elements into a Map.  The toMap( ) method has three forms. The first is:

Collectors toMap

If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. For example, consider the following example:

Collectors toMap

In this example, mapped keys have duplicates so the IllegalStateException is thrown. If the mapped keys might have duplicates, use the following form of toMap method to prevent this exception:

Collectors toMap


If you want to get specific type Map, use the following form of toMap:

Collectors toMap


Program

Collectors toMap

Program Source

import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.HashMap;

public class Javaapp {

    public static void main(String[] args) {
        
        String strary[] = {"Ida","Jack","Lia","Bryan","Edmund","Logan"};
        Stream<String> strstm = Stream.of(strary);
        HashMap<Integer,String> mp;
        mp = strstm.collect(Collectors.toMap((a)->a.length(), (a)->a, (a,b)->a+" / "+b, HashMap::new));
        System.out.println(mp);
    }
}

Leave a Comment