In Java, a filter is a function that takes an input and returns a boolean value indicating whether the input meets certain criteria. Filters are commonly used to select a subset of data based on certain criteria.
There are several ways to implement filters in Java. Here are some common approaches:
Predicate: A Predicate is a functional interface that represents a function that takes an input and returns a boolean value. You can use a Predicate to define a filter by implementing the test() method. Here's an example:import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
// Define a filter that checks if a number is even
Predicate<Integer> isEven = n -> n % 2 == 0;
// Test the filter
System.out.println(isEven.test(4)); // prints "true"
System.out.println(isEven.test(5)); // prints "false"
}
}
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c", "d", "e");
// Filter the list to get only strings that start with "b"
list.stream()
.filter(s -> s.startsWith("b"))
.forEach(System.out::println); // prints "b"
}
}
import java.util.Arrays;
import java.util.List;
public class Main {
public static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
// Filter the list to get only even numbers
list.stream()
.filter(Main::isEven)
.forEach(System.out::println); // prints "2 4 6"
}
}
These are just a few examples of how you can use filters in Java. You can find more information about filters and other functional programming concepts in the Java documentation.