在两个列表中的常见元素 [英] Common elements in two lists

查看:106
本文介绍了在两个列表中的常见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个的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?

推荐答案

使用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collection.html#retainAll%28java.util.Collection%29\"><$c$c>Collection#retainAll().

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆