21

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,083
  • 2
  • 10
  • 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

60

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,271
  • 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
  • 389,931
  • 88
  • 552
  • 692
5
if(!CollectionUtils.intersection(arrayList1, arrayList2).isEmpty()){
      // has common
}
else{
   //no common
}

use org.apache.commons.collections

Trying
  • 13,590
  • 8
  • 67
  • 109
4

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

Use like this:

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

Hope this helps.

vikingsteve
  • 36,466
  • 22
  • 106
  • 148
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
  • 161,154
  • 30
  • 262
  • 319
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
  • 24,731
  • 13
  • 95
  • 108