Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an ArrayList contains every element from another ArrayList (or Collection)

There is probably a simple one-liner that I am just not finding here, but this is my question:

How do I check if an ArrayList contains all of the objects in another ArrayList? I am looking (if it exists) for something along the lines of:

//INCORRECT EXAMPLE: if(one.contains(two)) {     return true; } else {     return false; } 

For example:

ArrayList one = {1, 2, 3, 4, 5}  ArrayList two = {1, 2, 3} --> True ArrayList two = {} --> True ArrayList two = {1, 2, 3, 4, 5} --> True ArrayList two = {1, 5, 2} --> True ArrayList two = {1, 7, 4} --> False ArrayList two = {0, 1, 3} --> False ArrayList two = {4, 5, 6} --> False ArrayList two = {7, 8, 9} --> False 
like image 697
Evorlor Avatar asked Jan 24 '13 22:01

Evorlor


People also ask

How do you check if an ArrayList contains another ArrayList?

The Java ArrayList containsAll() method checks whether the arraylist contains all the elements of the specified collection. The syntax of the containsAll() method is: arraylist. containsAll(Collection c);

How do you check if list contains an item from another list 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 two ArrayList has the same element?

use Collections. sort() on both list. Then use the equals() . This is O(nlogn), because you do two sorts, and then an O(n) comparison.

How do you check if an ArrayList contains an element?

contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.


2 Answers

There is a method called containsAll declared in the java.util.Collection interface. In your setting one.containsAll(two) gives the desired answer.

like image 57
C-Otto Avatar answered Sep 22 '22 21:09

C-Otto


Per the List interface:

myList.containsAll(...); 
like image 39
splungebob Avatar answered Sep 22 '22 21:09

splungebob