如何在多个列表中查找公共元素? [英] How to find common elements in multiple lists?

查看:113
本文介绍了如何在多个列表中查找公共元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表(嵌套列表)。我需要找到它们之间的共同元素。

I have a list of list (nest list). I need to find the common elements between those.

Example would be 
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]

应该导致[1,3]

如果不使用HashSet的retainAll方法,如何迭代所有要查找的元素?

If not using the retainAll method of HashSet, how to iterate all the element to find?

谢谢,

推荐答案

你能做什么:

Set<Integer> intersection = new HashSet<>(lists.get(0))
for(List<Integer> list : lists) {
    Set<Integer> newIntersection = new HashSet<>();
    for(Integer i : list) {
        if(intersection.contains(i)) {
            newIntersections.add(i);
        }
    }
    intersection = newIntersection;
}

这篇关于如何在多个列表中查找公共元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆