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 do I create a Map of age to hobbies like Map<Integer, Set<String>>?
The Java 8 way I cooked up is:
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 of doing this with Collectors.groupingBy() perhaps?
As a related question, I find the version without Java streams to be 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; specially when the streamed version, as seen here, has no intermediate streams with transformations of the data but quickly end in a terminal operation?