Elegantly create map with object fields as key/value from object stream in Java 8

随声附和 提交于 2019-12-04 14:06:52
Roland

As you noted yourself: the Stream solution might not be as readable as your current non-Stream-solution. Solving your problem with groupingBy might not look as good as you might expect as you want to transform your List into a Set.

I constructed a solution with groupingBy, mapping and reducing, but that solution is not that easy to read and did even contain an error. You can read more about that in: Java 8 stream.collect( ... groupingBy ( ... mapping( ... reducing ))) reducing BinaryOperator-usage I really suggest to look up the answer Holger gave as it also contains a simpler solution using a custom Collector and a little Outlook to Java 9's flatMapping, which for me comes close to your non-Stream-solution.

But another solution using groupingBy I came up with and that actually works is the following:

Map<Integer, Set<String>> yourmap;
yourmap = personList.stream()
                    .flatMap(p -> p.hobbies.stream()
                                           .flatMap(hobby -> Stream.of(new SimpleEntry<>(p.age, hobby)))
                            )
                    .collect(Collectors.groupingBy(Entry::getKey,
                             Collectors.mapping(Entry::getValue, Collectors.toSet())));

for that you need the following imports:

import java.util.AbstractMap.SimpleEntry;
import java.util.Map.Entry;

Of course you can take also a Tuple or Pair or what you like the most.

But then again not better in any ways.

I would stay with your current non-Stream-solution. It is more readable and does what it should do.

Look at similar example from Java 8 Collectors documentation:

Map<City, Set<String>> namesByCity
     = people.stream().collect(groupingBy(Person::getCity, TreeMap::new,                                           
           mapping(Person::getLastName, toSet())));

You could use the same approach here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!