Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect list of strings to map with Java 8 Stream API

Could someone suggest how could I transform list like ["bla", "blabla", "blablabla"] to map like {"bla" : 3, "blabla" : 6, "blablabla" : 9} with words stands for keys and values stands for words lengths?

I do something like:

Map<String, Integer> map =  list.stream().collect(Collectors.groupingBy(Function.identity(), String::length));

but have no luck.

Thank you!

like image 337
Dmitry Adonin Avatar asked Mar 27 '17 15:03

Dmitry Adonin


1 Answers

You were almost correct with groupingBy, but the second parameter of that is a Collector, not a Function. Thus I used toMap.

 Map<String, Integer> map = Stream.of("bla", "blabla", "blablabla").distinct()
            .collect(Collectors.toMap(Function.identity(), String::length));
like image 171
Eugene Avatar answered Oct 05 '22 16:10

Eugene