.stream().filter
时间: 2023-10-15 18:19:01 浏览: 64
The method `.filter()` is a method in Java 8's Stream API that takes a Predicate as an argument and returns a new Stream that contains only the elements that satisfy the given Predicate.
Here's an example of how to use `.filter()`:
```java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
```
In this example, we have a list of integers `numbers`. We create a Stream from this list using the `.stream()` method. We then apply the `.filter()` method to this Stream with a Predicate that checks if the number is even. This creates a new Stream that contains only the even numbers. Finally, we collect the filtered elements into a new List using the `.collect()` method.
阅读全文