我有以下课程
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;}
}
如何创建年龄到爱好的地图,例如Map<Integer, Set<String>>
?
我准备的 Java 8 方式是:
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())
)
);
有没有更惯用的方法来做到这一点Collectors.groupingBy()
也许?
作为一个相关的问题,我发现没有 Java 流的版本更具可读性。
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);
}
如果更容易阅读,我们是否应该使用非流代码?特别是当流版本(如此处所示)没有带有数据转换的中间流但很快以终端操作结束时?