What is a Predicate in Java and How to Use It
In Java, a predicate is a functional interface from the java.util.function package that represents a function that takes in one argument and returns a boolean value. The functional interface is defined as:
public interface Predicate<T> {
boolean test(T t);
}
The test()
method takes in a single argument of type T
and returns a boolean value indicating whether the input satisfies some condition.
Here's an example of how to use a predicate in Java. Let's say we have a list of integers and we want to filter out the even numbers. We can use a predicate to define the condition for filtering:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> isEven = n -> n % 2 == 0;
List<Integer> evenNumbers = numbers.stream()
.filter(isEven)
.collect(Collectors.toList());
System.out.println(evenNumbers); // [2, 4, 6, 8, 10]
}
}
In this example, we define a predicate called isEven
that checks if a given integer is even. We then use this predicate to filter the list of integers using the filter()
method of the Stream API, and collect the filtered results into a new list using the collect()
method. Finally, we print out the even numbers.
Here's another example that demonstrates how to use a predicate to filter a list of strings based on a certain condition
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("hello", "world", "java", "programming");
Predicate<String> startsWithJ = s -> s.startsWith("j");
List<String> jWords = words.stream()
.filter(startsWithJ)
.collect(Collectors.toList());
System.out.println(jWords); // [java]
}
}
In this example, we define a predicate called startsWithJ
that checks if a given string starts with the letter "j". We then use this predicate to filter the list of strings using the filter()
method of the Stream API, and collect the filtered results into a new list using the collect()
method. Finally, we print out the strings that start with "j".