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:
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:
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:
If you want to get specific type Map, use the following form of toMap:
Program
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); } }