怎么用stream流筛选两个集合的并集
时间: 2023-05-12 12:07:35 浏览: 101
可以使用Java 8中的Stream API来筛选两个集合的并集。首先将两个集合合并成一个集合,然后使用distinct()方法去重,最后将结果收集到一个新的集合中。以下是示例代码:
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(3, 4, 5);
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());
System.out.println(union); // [1, 2, 3, 4, 5]
注意,这里使用了Java 8中的Lambda表达式和方法引用,如果你不熟悉这些语法,可以先学习一下。
相关问题
写一个用stream流筛选两个集合的并集Demo
以下是一个用stream流筛选两个集合的并集的Demo:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
List<Integer> list2 = new ArrayList<>();
list2.add(3);
list2.add(4);
list2.add(5);
list2.add(6);
List<Integer> union = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println(union);
}
}
```
这个Demo中,我们创建了两个List,然后使用stream流筛选出它们的并集。具体来说,我们使用了filter()方法和contains()方法,filter()方法用于筛选出list1中包含在list2中的元素,contains()方法用于判断list2中是否包含某个元素。最后,我们使用collect()方法将筛选出的元素收集到一个新的List中,并输出这个List。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)