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.
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
-
-
-
I am not getting how to use this predicate and pass it in to argument. Can anyone give me demo ? – Chirag Jun 19 '14 at 11:51
-
1
You can use Google guavas Iterables.all
Iterables.all(collection, new Predicate() {
boolean apply(T element) {
.... //check your condition
}
}
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
max
andmin
make no sense per se, becauseCollection
is a generic type. for instance if you haveCollection<Object>
, what would bemax
andmin
? take a look here: stackoverflow.com/questions/122105/… – logoff Jun 19 '14 at 10:20