gpt4 book ai didi

java - 如何在多个列表中查找共同元素?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:06:29 25 4
gpt4 key购买 nike

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

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

应该导致 [1,3]

如果不使用HashSet的retainAll方法,如何遍历所有元素来查找?

谢谢,

最佳答案

你可以做什么:

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;
}

关于java - 如何在多个列表中查找共同元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com