如何使用相同的输入创建两个不同的补充列表

Man*_*ani 7 java java-stream

在我之前的问题 - 如何使用列表在地图中分组时过滤年龄我能够找到使用年龄组的名称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)

但我必须再次访问用户列表才能找到免费列表.这可以做得更简单吗?

Ous*_* D. 6

你是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)

  • @Mani你也应该知道,在内部它只使用一个带有两个键的专用地图,更快的查找然后是一个`HashMap` (2认同)

Nam*_*man 5

List.removeAll

您可以使用removeAll获取免费清单.

List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
userBelowThreshold.removeAll(userAboveThreshold);
Run Code Online (Sandbox Code Playgroud)

注意:这将需要重写equalshashCode实现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)