7

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!

1
  • 2
    You need to use Collectors.toMap. And make sure your stream is distinct(), otherwise you'll get an exception if you have duplicates in list. Commented Mar 27, 2017 at 15:52

2 Answers 2

8

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));
Sign up to request clarification or add additional context in comments.

1 Comment

It works with M. Prokhorov's suggestion about distinct. Thank you!
-1

You don't have to do something so complicated. Here is an example code:

...
... 

List<String> ll= // the list of words that you have.
Map<String,Integer> map = new HashMap<>();// or any other kind of map you want to create

for(String s:ll){
    map.put(s,s.length());
}

Now you have a map that satisfies your requirement.

1 Comment

It definitely works, but I'd like to solve it with streams in more accurate manner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.