Java 如何检查一个 ArrayList 是否包含另一个 ArrayList 的任何元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18943861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if an ArrayList contains any element of another ArrayList?
提问by Denman
Is there any way to determine whether an ArrayList contains any element of a different ArrayList?
有没有办法确定一个 ArrayList 是否包含不同 ArrayList 的任何元素?
Like this:
像这样:
list1.contains(any element of list2)
Is looping through all the elements of list2
and checking the elements one by one the only way?
循环遍历所有元素list2
并逐一检查元素是唯一的方法吗?
采纳答案by Bohemian
Although not highly efficient, this is terse and employs the API:
虽然效率不高,但这很简洁并且使用了 API:
if (!new HashSet<T>(list1).retainAll(list2).isEmpty())
// at least one element is shared
回答by Rahul Tripathi
How about trying like this:-
试试这样怎么样:-
List1.retainAll(List2)
like this:-
像这样:-
int a[] = {30, 100, 40, 20, 80};
int b[] = {100, 40, 120, 30, 230, 10, 80};
List<Integer> 1ist1= Arrays.asList(a);
List<Integer> 1ist2= Arrays.asList(b);
1ist1.retainsAll(1ist2);
回答by vikingsteve
If you have access to Apache Commons, see CollectionUtils.intersection(a,b)
如果您有权访问 Apache Commons,请参阅CollectionUtils.intersection(a,b)
Use like this:
像这样使用:
! CollectionUtils.intersection(list1, list2).isEmpty()
Hope this helps.
希望这可以帮助。
回答by davnicwil
If you're not constrained in using third-party libraries, Apache commons ListUtilsis good for common list operations.
如果您在使用第三方库方面不受限制,Apache commons ListUtils非常适合常见的列表操作。
In this case you could use the intersection
method
在这种情况下,您可以使用该intersection
方法
if(!ListUtils.intersection(list1,list2).isEmpty()) {
// list1 & list2 have at least one element in common
}
回答by Trying
if(!CollectionUtils.intersection(arrayList1, arrayList2).isEmpty()){
// has common
}
else{
//no common
}
use org.apache.commons.collections
用 org.apache.commons.collections
回答by Fallso
Consider the following: Java SE 7 documentation: java.util.Collections.disjoint
请考虑以下内容: Java SE 7 文档:java.util.Collections.disjoint
The "disjoint" method takes two collections (listA and listB for example) as parameters and returns "true" if they have no elements in common; thus, if they have any elements in common, it will return false.
“disjoint”方法将两个集合(例如listA和listB)作为参数,如果它们没有共同的元素,则返回“true”;因此,如果它们有任何共同元素,它将返回 false。
A simple check like this is all that's required:
只需要这样一个简单的检查:
if (!Collections.disjoint(listA, listB))
{
//List "listA" contains elements included in list "listB"
}