Java 8并行流并发分组 [英] Java 8 Parallel Stream Concurrent Grouping
本文介绍了Java 8并行流并发分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个类
Class Person {
String name;
String uid;
String phone;
}
我正在尝试按类的所有字段进行分组。如何在JAVA 8中使用并行流来转换
I am trying to group by all the fields of the class. How do i use parallel streams in JAVA 8 to convert a
List<Person> into Map<String,Set<Person>>
其中地图的关键字是类中每个字段的值。 JAVA 8以下示例分组由单个字段组成,如何将一个类的所有字段组成一个映射?
where the key of the map is the value of each field in the class . JAVA 8 the following example groups by a single field, how can i do it for all fields of a class into a single Map?
ConcurrentMap<Person.Sex, List<Person>> byGender =
roster
.parallelStream()
.collect(
Collectors.groupingByConcurrent(Person::getGender));
推荐答案
你可以使用<$ c $来做到这一点c> 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,以下方法可以优先于上述方法:
As Holger in the comments suggested, following approach can be preffered over the above one:
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
方法与我上面建议的陈述相同。
It uses the overloaded collect
method which acts identical to my suggested statement above.
这篇关于Java 8并行流并发分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文