I have a collection and I would like to know if at least one element meets some condition. Essentially, what some does in JavaScript, I would like to do on a collection!
You can use CollectionUtils from Apache commons-collections:
List primes = Arrays.asList(3, 5, 7, 11, 13)
CollectionUtils.exists(primes, even); //false
Where even
is a predicate:
Predicate even = new Predicate() {
public boolean evaluate(Object object) {
return ((Integer)object) % 2 == 0;
}
}
Or in an inlined version:
List primes = Arrays.asList(2, 3, 5, 7, 11, 13)
CollectionUtils.exists(primes, new Predicate() {
public boolean evaluate(Object object) {
return ((Integer)object) % 2 == 0;
}
});
Yes, it is ugly for two reasons:
commons-collections
does not support generics.On the other hand in modern JVM languages like Scala you can write:
List(3,5,7,11,13,17).exists(_ % 2 == 0)