list.stream().filter过滤list条件返回新list
时间: 2023-08-24 20:06:30 浏览: 71
是的,你可以使用Java 8中的Stream API来过滤List中的元素并返回一个新的List。具体来说,你可以使用filter()方法来指定一个Predicate(谓词)来过滤List中的元素,然后使用collect()方法将过滤后的元素收集到一个新的List中。以下是一个示例代码:
```
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> filteredList = list.stream()
.filter(i -> i % 2 == 0) // 过滤出偶数
.collect(Collectors.toList());
System.out.println(filteredList); // 输出 [2, 4]
```
在这个示例中,我们使用filter()方法过滤出List中的偶数,并使用collect()方法将它们收集到一个新的List中。最后,我们打印出新的List,它应该只包含偶数。
相关问题
list.stream().filter过滤多个list字符串条件返回新list
你可以使用多个filter()方法来实现多个条件的过滤。以下是一个示例代码:
```
List<String> list1 = Arrays.asList("apple", "banana", "orange", "grape");
List<String> list2 = Arrays.asList("red", "yellow", "green", "purple");
List<String> filteredList = list1.stream()
.filter(s -> s.length() > 5) // 过滤出长度大于5的字符串
.filter(s -> list2.contains(s.substring(0, 3))) // 过滤出前三个字符在list2中出现的字符串
.collect(Collectors.toList());
System.out.println(filteredList); // 输出 [orange, grape]
```
在这个示例中,我们有两个List,分别是list1和list2。我们首先使用第一个filter()方法过滤出长度大于5的字符串,然后使用第二个filter()方法过滤出前三个字符在list2中出现的字符串。最后,我们使用collect()方法将过滤后的字符串收集到一个新的List中,并打印出新的List。它应该只包含orange和grape这两个字符串,因为它们的前三个字符分别是ora和gra,在list2中出现过。
list.stream.filter模糊过滤
对于模糊过滤,你可以使用 `filter` 方法配合匿名函数来实现。假设你有一个字符串列表 `list`,你想要过滤出其中包含特定子串的元素,可以按照以下方式使用 `filter` 方法:
```java
List<String> filteredList = list.stream()
.filter(str -> str.contains("特定子串"))
.collect(Collectors.toList());
```
其中,`str -> str.contains("特定子串")` 是一个匿名函数,用于判断字符串是否包含特定子串。`filter` 方法会保留返回值为 `true` 的元素,最后使用 `collect` 方法将过滤后的元素收集到新的列表中。
你可以根据实际需求修改上述代码中的 "特定子串" 部分,以适应不同的模糊过滤条件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)