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?

1
  • If 'X contains an element of Y' is the main usecase for your collection, you may want to consider using Set instead. Commented Sep 22, 2013 at 12:41

6 Answers 6

63

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

very useful method 1.7 onwards... :D
I prefer this answer as it uses native Java methods only and there is no casting required.
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 

Comments

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

use org.apache.commons.collections

Comments

4

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

Use like this:

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

Comments

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

Comments

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
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.