java 8 stream 求两集合交集
时间: 2023-11-07 15:20:48 浏览: 99
可以使用Stream API的intersect方法:
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> result = list1.stream()
.distinct()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println(result); // [3, 4, 5]
相关问题
Java求两个集合交集
在Java中,我们可以使用集合框架提供的`intersection()`或者`retainAll()`方法来找到两个集合的交集。以下是两种常见方法:
1. **使用`retainAll()`**:
```java
List<String> list1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
List<String> list2 = new ArrayList<>(Arrays.asList("b", "c", "e"));
// 使用 retainAll() 方法找出交集
list1.retainAll(list2);
System.out.println("Intersection: " + list1); // 输出: [b, c]
```
这里,`retainAll()`会从第一个列表删除所有不在第二个列表中的元素,剩下的就是它们的交集。
2. **使用`stream()`和`filter()`**:
```java
Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c", "d"));
Set<String> set2 = new HashSet<>(Arrays.asList("b", "c", "e"));
// 使用 Stream API 寻找交集
set1.retainAll(set2.stream());
System.out.println("Intersection (Set): " + set1); // 输出: [b, c]
// 如果你想保持列表形式,可以转换回 List
List<String> listIntersection = set1.stream().collect(Collectors.toList());
System.out.println("Intersection (List): " + listIntersection); // 输出: [b, c]
```
这两种方法都会返回包含两个集合公共元素的结果。
java8两个集合取交集
可以使用Java 8的Stream API来实现两个集合取交集,具体方法如下:
```
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> intersection = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
System.out.println(intersection); // 输出 [3, 4, 5]
```
首先将第一个集合转换为Stream,然后过滤出第二个集合中也包含的元素,最后将结果收集到一个新的List中。
阅读全文
相关推荐
















