本文介绍了在两个列表中的常见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个的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?
推荐答案
使用<$c$c>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.
这篇关于在两个列表中的常见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!