list.stream().filter()
时间: 2023-04-28 09:05:46 浏览: 41
`list.stream().filter()` 是 Java 8 中 stream API 中的一个方法。它可以对原始的集合进行过滤,筛选出满足特定条件的元素,并返回一个新的流对象。其中 filter 方法的参数是一个 Predicate 对象,表示需要过滤的条件。
示例:
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNums = nums.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
// evenNums 现在是 [2, 4, 6]
在这个例子中,我们对 nums 这个列表进行了过滤,只保留了所有偶数,最后将结果收集到了一个新的列表中.
相关问题
list.stream.filter
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.
java List.stream.filter
Java中的List接口提供了一个stream方法,该方法返回一个流对象,可以使用流操作对列表进行处理。其中,filter操作是一种流操作,用于根据指定的条件过滤列表中的元素。
filter方法接受一个Predicate参数,该参数是一个函数式接口,用于定义过滤条件。在filter操作中,只有满足该条件的元素才会被保留下来,而不满足条件的元素将被剔除。最终,filter操作返回一个新的流对象,其中包含符合过滤条件的元素。
以下是使用List.stream.filter方法的示例代码:
```java
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 使用filter操作过滤只保留偶数
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(evenNumbers); // 输出:[2, 4, 6, 8, 10]
}
}
```