如何检查java集合的所有元素是否符合某个条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24304129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:23:32  来源:igfitidea点击:

how to check if all elements of java collection match some condition?

javacollections

提问by Chirag

I have an ArrayList<Integer>. I want to check if all elements of the list are greater then or less then certain condition. I can do it by iterating on each element. But I want to know if there is any method in Collection class to get the answer like we can do to find maximum or minimum with Collections.max()and Collections.min()respectively.

我有一个ArrayList<Integer>. 我想检查列表中的所有元素是否大于或小于特定条件。我可以通过迭代每个元素来做到这一点。但我想知道 Collection 类中是否有任何方法来获得答案,就像我们可以分别用Collections.max()和找到最大值或最小值一样Collections.min()

采纳答案by kajacx

If you have java 8, use stream's allMatchfunction (reference):

如果您有 java 8,请使用流的allMatch函数(参考):

 ArrayList<Integer> col = ...;
 col.stream().allMatch(i -> i>0); //for example all integers bigger than zero

回答by Pracede

You cannot check values without iterating on all elements of the list.

您不能在不迭代列表的所有元素的情况下检查值。

for(Integer value : myArrayList){

    if(value > MY_MIN_VALUE){
        // do my job
    }
}

I hope this will help

我希望这个能帮上忙

回答by amorfis

You can use Google guavas Iterables.all

你可以使用谷歌番石榴 Iterables.all

 Iterables.all(collection, new Predicate() {
    boolean apply(T element)  {
       .... //check your condition 
   } 
 }