Java 8 Predicate
Predicate
A Predicate interface represents a boolean-valued-function of an argument. This is mainly used to filter data from a Java Stream. The filter method of a stream accepts a predicate to filter the data and return a new stream satisfying the predicate. A predicate has a test() method which accepts an argument and returns a boolean value.
@Test
public void testPredicate(){
List<String> names = Arrays.asList("John", "Smith", "Samueal", "Catley", "Sie");
Predicate<String> nameStartsWithS = str -> str.startsWith("S");
names.stream().filter(nameStartsWithS).forEach(System.out::println);
In the above example, we have created a predicate which tests the names that start with S. This predicate is supplied to a stream.
Predicate also provides a few default and static method for composition and other purposes:
default Predicate<T> and(Predicate<? super T> other);
default Predicate<T> or(Predicate<? super T> other);
static <T> Predicate<T> isEquals(Object targetRef);
default Predicate<T> negate();
Following example demonstrates to use and method to compose predicates with multiple predicates.
@Test
public void testPredicateAndComposition(){
List<String> names = Arrays.asList("John", "Smith", "Samueal", "Catley", "Sie");
Predicate<String> startPredicate = str -> str.startsWith("S");
Predicate<String> lengthPredicate = str -> str.length() >= 5;
names.stream().filter(startPredicate.and(lengthPredicate)).forEach(System.out::println);
}
Comments
Post a Comment