list.stream.filter
时间: 2023-09-25 08:15:58 浏览: 94
使用List和Stream完成统计计算.zip
The `filter` method in Java 8 streams is used to select elements from a stream based on a given condition. It takes a `Predicate` as an argument, which is a functional interface that takes an element and returns a boolean value. The `filter` method returns a new `Stream` containing only the elements that satisfy the given condition.
Here's an example of using `filter` to get all even numbers from a 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); // [2, 4, 6, 8, 10]
```
In this example, we first create a list of integers using `Arrays.asList`. We then create a stream from this list using the `stream` method. We use `filter` to select only the even numbers by passing in a lambda expression that checks if the number is divisible by 2. Finally, we collect the filtered stream into a new list using the `collect` method.
阅读全文