这段代码实现了求多个集合的交集,并且去除了重复元素。代码接收一个 List<List> 参数,表示多个集合,返回一个 Set 类型的结果,表示交集。

首先判断输入的集合是否为空,如果为空,则返回 null。

然后创建一个 LinkedHashSet 集合 result,并将第一个集合 otherColls.get(0) 的元素添加到 result 中。

接下来遍历 otherColls 中的每个集合 otherColl,如果 otherColl 不为空,则调用 result 的 retainAll 方法,将 result 保留与 otherColl 的交集。

如果 otherColl 为空,则直接返回一个新创建的空 LinkedHashSet 集合。

最后返回 result 作为结果。

public static  Set<String> intersectionDistinct(List<List<String>> otherColls) {
    if (CollUtil.isEmpty(otherColls)) {
        return null;
    }
    final Set<String> result = new LinkedHashSet<>(otherColls.get(0));;
    for (List<String> otherColl : otherColls) {
        if (CollUtil.isNotEmpty(otherColl)) {
            result.retainAll(otherColl);
        } else {
            // 有一个空集合就直接返回空
            return new LinkedHashSet<>();
        }
    }
    return result;
}
Java 实现多个集合交集并去重 - intersectionDistinct 方法

原文地址: http://www.cveoy.top/t/topic/mba6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录