I have the following class
class Person { public String name; public int age; public List<String> hobbies; Person(String name, int age, List<String> hobbies) {this.name = name; this.age = age; this.hobbies = hobbies;} }
How to create an age map for a hobby, for example Map<Integer, Set<String>> ?
I developed a Java 8 method:
Map<Integer, Set<String>> collect8 = persons.stream() .collect( toMap( p -> p.age, p -> p.hobbies.stream().collect(toSet()), (hobbies1, hobbies2) -> Stream.concat(hobbies1.stream(), hobbies2.stream()).collect(toSet()) ) );
Is there a more idiomatic way to do this with Collectors.groupingBy() , perhaps?
As a related question, I believe that the version without Java threads is becoming more readable.
Map<Integer, Set<String>> collect7 = new HashMap<>(); for(Person p: persons) { Set<String> hobbies = collect7.getOrDefault(p.age, new HashSet<>()); hobbies.addAll(p.hobbies); collect7.put(p.age, hobbies); }
Should we go with non streams code if it is easier to read; especially when the streaming version, as can be seen here, does not have intermediate streams with data transformations, but quickly ends in a terminal operation?