public static <T> T findAndRemoveFirst(Iterable<? extends T> collection, Predicate<? super T> test) {
T value = null;
for (Iterator<? extends T> it = collection.iterator(); it.hasNext();)
if (test.test(value = it.next())) {
it.remove();
return value;
}
return null;
}
When we want to 将 List 中的多个元素放入一个新列表(使用谓词进行筛选) ,并将它们从现有列表中删除, I could not find a proper answer anywhere.
下面是我们如何使用 JavaStreamingAPI 分区来实现这一点。
Map<Boolean, List<ProducerDTO>> classifiedElements = producersProcedureActive
.stream()
.collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));
// get two new lists
List<ProducerDTO> matching = classifiedElements.get(true);
List<ProducerDTO> nonMatching = classifiedElements.get(false);
// OR get non-matching elements to the existing list
producersProcedureActive = classifiedElements.get(false);
通过这种方式,可以有效地从原始列表中删除经过筛选的元素,并将它们添加到新列表中。
Refer the 5.2. Collectors.PartitioningBy section of 这篇文章.