Nilotpal Nilotpal - 3 months ago 11x
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


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>>x.toString().length(),x->x));


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

Map<Integer, List<String>> map =;

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.