Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 449
Chirag Avatar asked Jun 19 '14 10:06

Chirag


2 Answers

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
like image 133
kajacx Avatar answered Dec 02 '22 03:12

kajacx


You can use Google guavas Iterables.all

 Iterables.all(collection, new Predicate() {
    boolean apply(T element)  {
       .... //check your condition 
   } 
 } 
like image 25
amorfis Avatar answered Dec 02 '22 01:12

amorfis