Nilotpal Nilotpal - 5 months ago 17
Java Question

Lambda Expression to create a map with Integer as key and List as value

Question : Solve the following via lambda Expressions. Given a list of Strings, create a map where

Key=Integer(string.length)
value=List


If two strings matches with the length, create a list of all such matching length of strings.

I have no clue as how to create a list for all matching strings lengths within the stream!! I tried the following way, which gives me exception of duplicate Key, which is obvious.

private static void changeToMap(List<String> listString)
{
Map<Integer, String> map=listString.stream().collect(Collectors.toMap(x->x.toString().length(),x->x));
System.out.println(map);
}

Answer

This is precisely what the groupingBy collector was designed to do:

Map<Integer, List<String>> map = 
    listString.stream().collect(Collectors.groupingBy(String::length));

Note, BTW, that your code defined map as Map<Integer, String>, whereas according to the description of the problem, it should be defined as Map<Integer, List<String>>, as the snippet above defines it.