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

荒凉一梦 提交于 2020-01-20 03:52:06

问题


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.


回答1:


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

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



回答2:


You can use Google guavas Iterables.all

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



回答3:


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



来源:https://stackoverflow.com/questions/24304129/how-to-check-if-all-elements-of-java-collection-match-some-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!