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

前端 未结 3 429
渐次进展
渐次进展 2020-12-16 11:57

I have an ArrayList. 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 eac

相关标签:
3条回答
  • 2020-12-16 12:28

    You can use Google guavas Iterables.all

     Iterables.all(collection, new Predicate() {
        boolean apply(T element)  {
           .... //check your condition 
       } 
     } 
    
    0 讨论(0)
  • 2020-12-16 12:48

    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
    
    0 讨论(0)
  • 2020-12-16 12:55

    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

    0 讨论(0)
提交回复
热议问题