list.stream().filter()
时间: 2023-10-13 11:20:35 浏览: 16
这段代码是使用 Java 8 中的 Stream API 对 List 进行筛选操作。其中,filter() 方法是 Stream API 中的一个中间操作,用于筛选出符合某个条件的元素,并将其放入一个新的 Stream 中。示例代码如下:
```
List<String> list = Arrays.asList("apple", "banana", "orange", "grape");
Stream<String> filteredStream = list.stream().filter(s -> s.startsWith("a"));
```
这段代码会筛选出 List 中所有以字母 "a" 开头的字符串,并将它们放入一个新的 Stream 中。在上面的示例中,filteredStream 中的元素就是 "apple"。
相关问题
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]
}
}
```