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?
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?
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"
}
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
if(!CollectionUtils.intersection(arrayList1, arrayList2).isEmpty()){
// has common
}
else{
//no common
}
use org.apache.commons.collections
If you have access to Apache Commons, see CollectionUtils.intersection(a,b)
Use like this:
! CollectionUtils.intersection(list1, list2).isEmpty()
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);
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
}