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.
Asked
Active
Viewed 3.0k times
25

Chirag
- 455
- 1
- 4
- 18
-
If i'm not wrong, Collections.max() and Collections.min() also iterate through each element. – Kartik_Koro Jun 19 '14 at 10:19
-
`max` and `min` make no sense per se, because `Collection` is a generic type. for instance if you have `Collection – logoff Jun 19 '14 at 10:20
4 Answers
61
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
-
1
-
-
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
-
Should probably be noted that the above solution will return true for an empty list. – stackbacker Jul 13 '23 at 15:09
8
You can use Google guavas Iterables.all
Iterables.all(collection, new Predicate() {
boolean apply(T element) {
.... //check your condition
}
}

amorfis
- 15,390
- 15
- 77
- 125
0
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

JoaoFilipeClementeMartins
- 1,770
- 5
- 28
- 61

Pracede
- 4,226
- 16
- 65
- 110
0
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>?

Michael Pichler
- 1
- 2