23

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?

Denman
  • 1,233
  • 2
  • 11
  • 9
  • If 'X contains an element of Y' is the main usecase for your collection, you may want to consider using Set instead. – maasg Sep 22 '13 at 12:41

6 Answers6

64

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"
}
Fallso
  • 1,311
  • 1
  • 9
  • 18
8

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 
Bohemian
  • 412,405
  • 93
  • 575
  • 722
5
if(!CollectionUtils.intersection(arrayList1, arrayList2).isEmpty()){
      // has common
}
else{
   //no common
}

use org.apache.commons.collections

Trying
  • 14,004
  • 9
  • 70
  • 110
4

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

Use like this:

! CollectionUtils.intersection(list1, list2).isEmpty()
halfer
  • 19,824
  • 17
  • 99
  • 186
vikingsteve
  • 38,481
  • 23
  • 112
  • 156
3

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);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

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
}
davnicwil
  • 28,487
  • 16
  • 107
  • 123