假设我有一个列表,在其中执行了多个流操作。
这意味着我可以做以下事情:
bobs = myList.stream()
.filter(person -> person.getName().equals("Bob"))
.collect(Collectors.toList())
...
并且
tonies = myList.stream()
.filter(person -> person.getName().equals("tony"))
.collect(Collectors.toList())
我可以不只这样做吗:
Stream<Person> stream = myList.stream();
这意味着我可以做以下事情:
bobs = stream.filter(person -> person.getName().equals("Bob"))
.collect(Collectors.toList())
tonies = stream.filter(person -> person.getName().equals("tony"))
.collect(Collectors.toList())
.filter
超过一次(或任何其他操作),因为Stream是一个“管道”,任何操作(无论是否是最终操作)都会向管道添加一个新的“leg”,“封闭”原始管道输出;然后你必须使用新管道leg的输出,以此类推。这也看起来像是XY问题。你应该真正解释你想要做什么,这将避免人们猜测并帮助你得到你实际问题的答案。 - M. ProkhorovMap<Boolean,List<Person>> map = stream.filter(p -> p.getName().matches("Bob|tony")) .collect(Collectors.partitioningBy(p -> p.getName().equals("Bob"))); bobs = map.get(true); tonies = map.get(false);
- HolgergroupingBy
代替partitioningBy
很容易。但只要是二元选择,partitioningBy
具有性能优势。更重要的是要识别“我如何流两次?”作为一个xy问题,这将有助于通过正确的思维方式解决即使是完全不同的未来问题。 - Holger