Java Predicate : Clean way to test if else
In Java, a predicate is a functional interface that represents a boolean-valued function of an input argument. The predicate interface is part of the java.util.function package and has a single method called test()
.
The test()
method takes an argument of a certain type and returns a boolean value. It can be used to perform a test on the input argument and return a true or false value based on the outcome of the test.
Here’s an example of how to use the predicate interface in Java:
import java.util.function.Predicate;
public class Example {
public static void main(String[] args) {
// creating a predicate to test if a string is empty
Predicate<String> isEmpty = s -> s.isEmpty();
// testing the predicate
System.out.println(isEmpty.test("")); // true
System.out.println(isEmpty.test("Hello")); // false
}
}
We then test the predicate by calling its test()
method with two different string values. The first test returns true because the string is empty, and the second test returns false because the string is not empty.
Predicates are commonly used in Java to filter collections or arrays based on certain conditions. For example, you can use a predicate to filter out all the even numbers from an array of integers. Here’s an example:
import java.util.Arrays;
import java.util.function.Predicate;
public class Example {
public static void main(String[] args) {
// creating an array of integers
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// creating a predicate to filter out even numbers
Predicate<Integer> isEven = n -> n % 2 == 0;
// using the predicate to filter the array
Integer[] evenNumbers = Arrays.stream(numbers)
.filter(isEven)
.toArray(Integer[]::new);
// printing the filtered array
System.out.println(Arrays.toString(evenNumbers));
}
}In this example, we first create an array of integers. We then create a predicate called isEven that checks if an integer is even or not. We use the filter() method of the Stream interface to filter out all the even numbers from the array. Finally, we convert the filtered Stream into an array using the toArray() method and print it out.