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
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);
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.
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.
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.
There is a method called containsAll
declared in the java.util.Collection
interface. In your setting one.containsAll(two)
gives the desired answer.
Per the List interface:
myList.containsAll(...);
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