Chirag
Chirag

Reputation: 525

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

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.

Upvotes: 28

Views: 35335

Answers (4)

Michael Pichler
Michael Pichler

Reputation: 11

The answer col.stream().allMatch is the best solution for the original task, i.e. to check if all elements fulfill some condition.

If you instead want to find the min or max int value of a Stream/Collection you must first convert it to an IntStream using col.stream().mapToInt(ToIntFunction) where the ToIntFunction can be MyObject::getIntvalue or o -> o.getIntValue() or Integer::intValue if you already have a List<Integer> as explained on How do I get an IntStream from a List<Integer>?

Upvotes: 0

amorfis
amorfis

Reputation: 15770

You can use Google guavas Iterables.all

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

Upvotes: 8

Pracede
Pracede

Reputation: 4371

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

Upvotes: 0

kajacx
kajacx

Reputation: 12959

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

Upvotes: 64

Related Questions