Java 8 流 api 是一个非常好的功能,我非常喜欢它。让我感到不安的一件事是,90% 的时间我都希望将输入作为集合,将输出作为集合。结果是我必须一直调用 stream()
和 collect()
方法:
collection.stream().filter(p->p.isCorrect()).collect(Collectors.toList());
是否有任何 java api 可以让我跳过流并直接对集合进行操作(如 c# 中的 linq
?):
collection.filter(p->p.isCorrect)
最佳答案
是的,使用 Collection#removeIf(Predicate)
:
Removes all of the elements of this collection that satisfy the given predicate.
请注意,它会更改给定的集合,而不是返回一个新集合。但是您可以创建集合的副本并对其进行修改。另请注意,谓词需要被否定才能充当过滤器:
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered,
Predicate<? super E> filter) {
List<E> copyList = new ArrayList<>(unfiltered);
// removeIf takes the negation of filter
copyList.removeIf(e -> { return !filter.test(e);});
return copyList;
}
但正如@Holger 在评论中所建议的那样,如果您选择在代码中定义此实用程序方法并在需要获得过滤集合的任何地方使用它,那么只需将调用委托(delegate)给 collect
该实用程序中的方法。你的调用者代码会更简洁。
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered,
Predicate<? super E> filter) {
return unfiltered.stream()
.filter(filter)
.collect(Collectors.toList());
}
关于Java 8 - 省略了繁琐的收集方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124120/