java取集合交集数量大的集合
时间: 2023-08-23 16:08:17 浏览: 95
可以通过遍历集合中的元素,计算交集的数量来实现。具体实现如下:
```java
public static <T> Set<T> maxIntersection(Collection<Set<T>> sets) {
Set<T> maxSet = Collections.emptySet();
int maxSize = 0;
for (Set<T> set : sets) {
int size = 0;
for (Set<T> other : sets) {
if (set != other) {
size += intersection(set, other).size();
}
}
if (size > maxSize) {
maxSet = set;
maxSize = size;
}
}
return maxSet;
}
public static <T> Set<T> intersection(Set<T> set1, Set<T> set2) {
Set<T> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
return intersection;
}
```
这里定义了两个方法,`maxIntersection()` 方法接收一个 `Collection<Set<T>>`,返回交集数量最大的集合。`intersection()` 方法计算两个 `Set` 集合的交集。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.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)
![](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)