如何使用相同的输入创建两个不同的互补列表 [英] How do I create two different compliementary lists using same input

查看:48
本文介绍了如何使用相同的输入创建两个不同的互补列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的问题中-如何在使用列表分组地图时过滤年龄我能够使用List<User> users找到年龄组的名称.现在,我尝试根据阈值查找不同年龄段的用户组.我尝试过

In my previous question - How to filter the age while grouping in map with list I was able to find the name to age groups using List<User> users. Now I am trying to find the different User groups from ages according to the threshold. I tried this

List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());

这次可以用了

userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));

但是我必须再次访问用户列表才能找到免费列表.难道这不简单吗?

But I have to access the users list again to find the complimentary list. Can this not be done simpler?

推荐答案

您正在使用partitioningBy收集器:

Map<Boolean, List<User>> result = 
             users.stream().collect(partitioningBy(u -> u.getAge() > 21));

然后按如下所示使用它:

Then use it as follows:

List<User> userAboveThreshold = result.get(true);
List<User> userBelowThreshold = result.get(false);

这篇关于如何使用相同的输入创建两个不同的互补列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆