在两个列表中的常见元素

问题描述:

我有两个的ArrayList 3的整数。我想找到一种方法,返回两个列表的共同元素。有anynody想法,我怎么能做到这一点?

I have two arrayLists with 3 integer. I want to find a way to return the common elements of the two lists. Has anynody idea, how can I achieve this?

使用Collection#retainAll()$c$c>.

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.