Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an ArrayList contains any element of another ArrayList? [duplicate]

Tags:

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?

like image 753
Denman Avatar asked Sep 22 '13 12:09

Denman


People also ask

How do you find if ArrayList contains duplicates or not?

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.

How do you check if an ArrayList contains another ArrayList?

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.

How do you check if all items in a list are in another list Java?

The containsAll() method of List interface in Java is used to check if this List contains all of the elements in the specified Collection.

Does ArrayList contain duplicates?

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.


2 Answers

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" } 
like image 83
Fallso Avatar answered Oct 13 '22 11:10

Fallso


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  
like image 33
Bohemian Avatar answered Oct 13 '22 12:10

Bohemian