两个列表中的公共元素 [英] Common elements in two lists
本文介绍了两个列表中的公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个 ArrayList
对象,每个对象有三个整数.我想找到一种方法来返回两个列表的公共元素.有人知道我如何实现这一目标吗?
I have two ArrayList
objects with three integers each. I want to find a way to return the common elements of the two lists. Has anybody an idea how I can achieve this?
推荐答案
listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.
如果您想避免 listA
中的更改受到影响,那么您需要创建一个新的.
If you want to avoid that changes are being affected in listA
, then you need to create a new one.
List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.
这篇关于两个列表中的公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文