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!
As of Java 8, you can convert the Collection into a Stream and use anyMatch as in the following example.
import java.util.Arrays;
import java.util.List;
public class SomeExample {
public static void main(String[] args) {
List list = Arrays.asList(1, 2, 3, 4, 5, -6, 7);
boolean hasNegative = list.stream().anyMatch(x -> x < 0);
if (hasNegative) {
System.out.println("List contains some negative number");
}
else {
System.out.println("List does not contain any negative number");
}
}
}