本文介绍了是否可以按功能对流进行分组和分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在对流进行分组和划分,如下所示:
I am grouping and partioning a stream as follows:
// Partioning
Map<Boolean, List<Person>> partitioned = persons.stream().
collect(Collectors.partitioningBy(p -> p.getAge() > 20));
// Grouping
Map<String, List<Person>> grouped = persons.stream()
.collect(Collectors.groupingBy(p -> p.getCity()));
有没有办法我可以将两者结合起来?我尝试在partioningBy内使用groupingBy两者结合使用,但没有把事情做对.有什么建议吗?
Is there a way i can combine both of these? I tried combining both with using groupingBy inside partioningBy, but did not get the things right. Any suggestion?
预期结果是对姓名以P开头的人员进行划分,并按年龄分组.这是人员列表:
The expected result is the partition the persons with those whose name starts with P and group them by age.Here is the persons list:
List<Person> persons = Arrays.asList(
new Person("Max", 18),
new Person("Peter", 23),
new Person("Pamela", 23),
new Person("David", 12),
new Person("Pam", 12));
推荐答案
我尝试了以下操作,并了解了它的工作原理.
I tried the following and somhow it worked.
Map<Boolean, Map<Object, List<Person>>> rr = persons.stream()
.collect(Collectors.partitioningBy(p -> p.name.startsWith("P"),
Collectors.groupingBy(p -> p.age > 20)));
输出符合预期
rr = {false={false=[Max, David]}, true={false=[Pam], true=[Peter, Pamela]}}
但是,我不确定这是否是有效的方法.有什么建议吗?
But, i am not sure is it the efficient way to do this. Any suggestions?
这篇关于是否可以按功能对流进行分组和分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!