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?
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection.
ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With