两个列表中的公共元素
问题描述:
我有两个 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.