gpt4 book ai didi

Java 8 并行流并发分组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:40 27 4
gpt4 key购买 nike

假设我有一个类

Class Person {
String name;
String uid;
String phone;
}

我正在尝试按类(class)的所有领域进行分组。我如何在 JAVA 8 中使用并行流来转换一个

List<Person> into Map<String,Set<Person>>

其中映射的键是类中每个字段的值。 JAVA 8 以下示例按单个字段分组,我如何将一个类的所有字段放入单个 Map 中?

ConcurrentMap<Person.Sex, List<Person>> byGender =
roster
.parallelStream()
.collect(
Collectors.groupingByConcurrent(Person::getGender));

最佳答案

您可以使用Collector 中的of 静态工厂方法来做到这一点:

Map<String, Set<Person>> groupBy = persons.parallelStream()
.collect(Collector.of(
ConcurrentHashMap::new,
( map, person ) -> {
map.computeIfAbsent(person.name, k -> new HashSet<>()).add(person);
map.computeIfAbsent(person.uid, k -> new HashSet<>()).add(person);
map.computeIfAbsent(person.phone, k -> new HashSet<>()).add(person);
},
( a, b ) -> {
b.forEach(( key, set ) -> a.computeIfAbsent(key, k -> new HashSet<>()).addAll(set));
return a;
}
));

正如 Holger 在评论中所建议的,以下方法优于上述方法:

Map<String, Set<Person>> groupBy = persons.parallelStream()
.collect(HashMap::new, (m, p) -> {
m.computeIfAbsent(p.name, k -> new HashSet<>()).add(p);
m.computeIfAbsent(p.uid, k -> new HashSet<>()).add(p);
m.computeIfAbsent(p.phone, k -> new HashSet<>()).add(p);
}, (a, b) -> b.forEach((key, set) -> {
a.computeIfAbsent(key, k -> new HashSet<>()).addAll(set));
});

它使用重载的 collect 方法,其行为与我上面建议的语句相同。

关于Java 8 并行流并发分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com