我有一个列表列表(嵌套列表)。我需要找到它们之间的共同元素。
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/