【发布时间】:2017-03-23 04:58:27
【问题描述】:
我有以下课程
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);
}
如果更容易阅读,我们是否应该使用非流代码?特别是当流式版本(如此处所示)没有带有数据转换的中间流但很快以终端操作结束时?
【问题讨论】:
-
永远不要仅仅因为它们花哨而使用流——如果命令式版本看起来更容易阅读,坚持下去!流是一种工具,因此它们对一些问题有用,而不是全部。
标签: java java-8 java-stream collectors