list.stream().filter()
时间: 2023-09-25 07:15:49 浏览: 106
The `filter()` method in Java's `Stream` class is used to create a new stream that contains only the elements from the original stream that meet a certain condition. It takes a `Predicate` as an argument, which is a functional interface that takes an element from the stream and returns a boolean value indicating whether the element should be included in the new stream.
Here's an example of using `filter()` to create a new stream of even numbers from an existing list of integers:
```
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, the `filter()` method is called on the `numbers` stream with a lambda expression that checks if the current element is even by using the modulo operator (`n % 2 == 0`). The resulting stream only contains the even numbers, which are collected into a new list using the `collect()` method with the `Collectors.toList()` collector.
Note that the original `numbers` list is not modified by this operation, as streams are immutable and do not change the underlying data structure.
阅读全文