How to filter a Java Collection (based on predicate)?
To filter a Java Collection based on a predicate, you can use the filter()
method of the Stream
interface. The filter()
method takes a predicate as an argument and returns a stream containing only the elements that match the given predicate.
Here's an example of how you can use the filter()
method to filter a List
of integers based on a predicate:
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Create a predicate that filters out even numbers
Predicate<Integer> isOdd = n -> n % 2 != 0;
// Use the filter() method to create a stream of odd numbers
List<Integer> oddNumbers = numbers.stream()
.filter(isOdd)
.collect(Collectors.toList());
System.out.println(oddNumbers); // [1, 3, 5, 7, 9]
}
}
In this example, the filter()
method is used to create a stream of odd numbers from the numbers
list. The collect()
method is then used to collect the elements of the stream into a new List
.
I hope this helps! Let me know if you have any questions.