[英]Using Java streams, how to filter a collection such that the result contains all elements up until a match is found?
[英]how to check if all elements of java collection match some condition?
我有一个ArrayList<Integer>
。 我想检查列表中的所有元素是否大于或小于某个条件。 我可以通过迭代每个元素来做到这一点。 但我想知道Collection类中是否有任何方法可以获得答案,就像我们可以分别使用Collections.max()
和Collections.min()
来查找最大值或最小值。
如果您有java 8,请使用stream的allMatch
函数( 参考 ):
ArrayList<Integer> col = ...;
col.stream().allMatch(i -> i>0); //for example all integers bigger than zero
您可以使用Google guavas Iterables.all
Iterables.all(collection, new Predicate() {
boolean apply(T element) {
.... //check your condition
}
}
如果不迭代列表的所有元素,则无法检查值。
for(Integer value : myArrayList){
if(value > MY_MIN_VALUE){
// do my job
}
}
我希望这个能帮上忙
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.