[英]How do I create two different compliementary lists using same input
在我之前的問題 - 如何使用列表在地圖中分組時過濾年齡我能夠使用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());
這次它可以工作,我可以看到使用
userAboveThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
userBelowThreshold.forEach(u -> System.out.println(u.getName() + " " + u.getAge()));
但我必須再次訪問用戶列表才能找到免費列表。 這可以做得更簡單嗎?
你是在partitioningBy
收藏家之后:
Map<Boolean, List<User>> result =
users.stream().collect(partitioningBy(u -> u.getAge() > 21));
然后使用如下:
List<User> userAboveThreshold = result.get(true);
List<User> userBelowThreshold = result.get(false);
List.removeAll
您可以使用removeAll
獲取免費列表。
List<User> userBelowThreshold = new ArrayList<>(users); // initiated with 'users'
userBelowThreshold.removeAll(userAboveThreshold);
注意 :這將需要覆蓋User
重寫equals
和hashCode
實現。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.