This java example will demonstrate how to check if any element in an arraylist satisfies a specified condition. In the @setUp method we will initialize an arraylist of Vehicles which we will use in the snippets below.
Setup
Straight up Java
This snippet will show how to check if the collection contains any elements that match a specified criteria using java. It will use a java enhanced for loop and check if any of the vehicles in the list are five years or older. If the condition is met, we will break the loop after setting the vehiclesFiveYearOrOlder to true.
Java 8
This snippet will check if any element in an arraylist matches a specified condition using java 8. Using the Streams API introduced in Java 8, we will call Stream.anyMatch, a terminal operation, passing in a java predicate created by a lambda expression. This condition will check if a vehicle manufacturer equals "Dodge".
Google Guava
Using Iterables, a guava collection utility, we will call Iterables.any passing a guava predicate which will return true if any vehicle manufacturer equals "Dodge".
Apache Commons
Similar to guava and java predicate, apache commons also has a predicate. Below we will call CollectionsUtils.exists passing it a apache commons predicate that will return true if at least one vehicle model contains "YUKON".