How can I check if an ArrayList contains any element of another ArrayList? [duplicate]

跟風遠走 提交于 2020-05-14 14:43:06

问题


Is there any way to determine whether an ArrayList contains any element of a different 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?


回答1:


Although not highly efficient, this is terse and employs the API:

if (!new HashSet<T>(list1).retainAll(list2).isEmpty())
    // at least one element is shared 



回答2:


Consider the following: Java SE 7 documentation: 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.

A simple check like this is all that's required:

if (!Collections.disjoint(listA, listB))
{
  //List "listA" contains elements included in list "listB"
}



回答3:


If you have access to Apache Commons, see CollectionUtils.intersection(a,b)

Use like this:

! CollectionUtils.intersection(list1, list2).isEmpty()

Hope this helps.




回答4:


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);



回答5:


if(!CollectionUtils.intersection(arrayList1, arrayList2).isEmpty()){
      // has common
}
else{
   //no common
}

use org.apache.commons.collections




回答6:


If you're not constrained in using third-party libraries, Apache commons ListUtils is good for common list operations.

In this case you could use the intersection method

if(!ListUtils.intersection(list1,list2).isEmpty()) {
    // list1 & list2 have at least one element in common
}


来源:https://stackoverflow.com/questions/18943861/how-can-i-check-if-an-arraylist-contains-any-element-of-another-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!