在我之前的问题 - 如何使用列表在地图中分组时过滤年龄我能够找到使用年龄组的名称List<User> users.现在我试图根据阈值从年龄中找到不同的用户组.我试过这个
List<User> userAboveThreshold = users.stream().filter(u -> u.getAge() > 21).collect(toList());
List<User> userBelowThreshold = users.stream().filter(u -> u.getAge() <= 21).collect(toList());
Run Code Online (Sandbox Code Playgroud)
这次它可以工作,我可以看到使用
userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
Run Code Online (Sandbox Code Playgroud)
但我必须再次访问用户列表才能找到免费列表.这可以做得更简单吗?
你是partitioningBy收藏家之后:
Map<Boolean, List<User>> result =
users.stream().collect(partitioningBy(u -> u.getAge() > 21));
Run Code Online (Sandbox Code Playgroud)
然后使用如下:
List<User> userAboveThreshold = result.get(true);
List<User> userBelowThreshold = result.get(false);
Run Code Online (Sandbox Code Playgroud)
List.removeAll您可以使用removeAll获取免费清单.
List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
userBelowThreshold.removeAll(userAboveThreshold);
Run Code Online (Sandbox Code Playgroud)
注意:这将需要重写equals和hashCode实现User.
Collectors.partitioningBy在另一方面,如果你需要进一步将遍历完整users列表只有一次,你可以使用Collectors.partitioningBy如下:
Map<Boolean, List<User>> userAgeMap = users.stream()
.collect(Collectors.partitioningBy(user -> user.getAge() > 21, Collectors.toList()));
List<User> userAboveThreshold = userAgeMap.get(Boolean.TRUE);
List<User> userBelowThreshold = userAgeMap.get(Boolean.FALSE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |