Java arraylist contains all

What is the ArrayList.containsAll() method in Java?

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

The ArrayList.containsAll() method in Java is used to check if the list contains all the elements present in a collection.

Syntax

The ArrayList.containsAll() method in Java can be declared as shown in the code snippet below:

boolean containsAll(Collection c) 
  • c : The collection whose elements will be checked if they are present in the list.

Return value

The ArrayList.containsAll() method returns a boolean , such that:

  • The return value is true if the list contains all the elements present in the collection c .
  • The return value is false if the list does not contain all the elements present in the collection c .

Note: If the collection is null , the ArrayList.containsAll() method throws the NullPointerException .

Examples

Example 1

Consider the code snippet below, which demonstrates the use of the ArrayList.containsAll() method.

import java.util.*;
public class Example1
public static void main(String args[])
List list1 = new ArrayList();
list1.add("Hello");
list1.add("world");
list1.add("!");
System.out.println("list1: " + list1);
List list2 = new ArrayList();
list2.add("Hello");
list2.add("world2");
System.out.println("list2: " + list2);
System.out.println("list1.containsAll(): " + list1.containsAll(list2));
>
>

Explanation

Two lists, list1 and list2 , are declared in line 7 and line 13 respectively. The ArrayList.containsAll() method is used in line 18 to check if all the elements of list2 are present in list1 . The ArrayList.containsAll() method returns false , which means that list1 does not contain all the elements in list2 .

Example 2

Consider another example of the ArrayList.containsAll() method.

import java.util.*;
public class Example2
public static void main(String args[])
List list1 = new ArrayList();
list1.add("Hello");
list1.add("world");
list1.add("!");
System.out.println("list1: " + list1);
List list2 = new ArrayList();
list2.add("Hello");
list2.add("world");
System.out.println("list2: " + list2);
System.out.println("list1.containsAll(): " + list1.containsAll(list2));
>
>

Explanation

Two lists, list1 and list2 , are declared in line 7 and line 13 respectively. The ArrayList.containsAll() method is used in line 18 to check if all the elements of list2 are present in list1 . The ArrayList.containsAll() method returns true , which means that list1 contains all the elements in list2 .

Learn in-demand tech skills in half the time

Источник

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Java ArrayList containsAll()

Note: We can say that the containsAll() method checks if the collection is a subset of the arraylist.

Example 1: Java ArrayList containsAll()

import java.util.ArrayList; class Main < public static void main(String[] args) < // create an ArrayList ArrayListlanguages1 = new ArrayList<>(); // insert element to the ArrayList languages1.add("JavaScript"); languages1.add("Python"); languages1.add("Java"); System.out.println("ArrayList 1: " + languages1); // create another ArrayList ArrayList languages2 = new ArrayList<>(); // add elements to ArrayList languages2.add("Java"); languages2.add("Python"); System.out.println("ArrayList 2: " + languages2); // check if ArrayList 1 contains ArrayList 2 boolean result1 = languages1.containsAll(languages2); System.out.println("ArrayList 1 contains all elements of ArrayList 2: " + result1); // check if ArrayList 2 contains ArrayList 1 boolean result2 = languages2.containsAll(languages1); System.out.println("ArrayList 2 contains all elements of ArrayList 1: " + result2); > >
ArrayList 1: [JavaScript, Python, Java] ArrayList 2: [Java, Python] ArrayList 1 contains all elements of ArrayList 2: true ArrayList 2 contains all elements of ArrayList 1: false

In the above example, we have created two arraylists named languages1 and languages2 . Notice the expression,

// return true languages1.containsAll(languages2)

Here, the containsAll() method checks if languages1 contains all elements of languages2 . Hence, the method returns true . However, notice the following expression,

// return false languages2.containsAll(languages1)

Here, the containsAll() method checks if languages2 contains all elements of languages1 . Hence, it returns false .

Note: The containsAll() method is not specific to the ArrayList class. The class inherits from the List interface.

Example 2: containsAll() Between Java ArrayList and HashSet

import java.util.ArrayList; import java.util.HashSet; class Main < public static void main(String[] args) < // create an ArrayList ArrayListnumbers = new ArrayList<>(); // add element to ArrayList numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("ArrayList: " + numbers); // create a HashSet HashSet primeNumbers = new HashSet<>(); // add elements to HashSet primeNumbers.add(2); primeNumbers.add(3); System.out.println("HashSet: " + primeNumbers); // check if ArrayList contains all elements of HashSet boolean result1 = numbers.containsAll(primeNumbers); System.out.println("ArrayList contains all elements of HashSet: " + result1); // check if HashSet contains all elements of ArrayList boolean result2 = primeNumbers.containsAll(numbers); System.out.println("HashSet contains all elements of ArrayList: " + result2); > >
ArrayList: [1, 2, 3] HashSet: [2, 3] ArrayList contains all elements of HashSet: true HashSet contains all elements of ArrayList: false

In the above example, we have created an arraylist named numbers and a hashset named primeNumbers . Notice the expressions,

// check if ArrayList contains HashSet // return true numbers.containsAll(primeNumbers) // check if HashSet contains ArrayList // return false primeNumbers.containsAll(numbers)

Note: We can get the common elements between ArrayList and HashSet using the Java ArrayList retainAll() method.

Источник

Program: How to find does ArrayList contains all list elements or not?

Here we can see example for finding whether the instance of an ArrayList contains all objects of another Collection instance. Here we are checking with another List instance.

package com.java2novice.arraylist; import java.util.ArrayList; import java.util.List; public class MyElementCheck < public static void main(String a[])< ArrayListarrl = new ArrayList(); arrl.add("First"); arrl.add("Second"); arrl.add("Third"); arrl.add("Random"); List list = new ArrayList(); list.add("Second"); list.add("Random"); System.out.println("Does ArrayList contains all list elements?: " +arrl.containsAll(list)); list.add("one"); System.out.println("Does ArrayList contains all list elements?: " +arrl.containsAll(list)); > >
Does ArrayList contains all list elements?: true Does ArrayList contains all list elements?: false

List Of All ArrayList Sample Programs:

  1. Basic ArrayList Operations.
  2. How to read all elements in ArrayList by using iterator?
  3. How to copy or clone a ArrayList?
  4. How to add all elements of a list to ArrayList?
  5. How to delete all elements from my ArrayList?
  6. How to find does ArrayList contains all list elements or not?
  7. How to copy ArrayList to array?
  8. How to get sub list from ArrayList?
  9. How to sort ArrayList using Comparator?
  10. How to reverse ArrayList content?
  11. How to shuffle elements in ArrayList?
  12. How to swap two elements in a ArrayList?
  13. How to convert list to csv string format?

Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.

There is a great difference between worry and concern. A worried person sees a problem, and a concerned person solves a problem.

About Author

I’m Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected] .

Most Visited Pages

Источник

Читайте также:  Inserting in string java
Оцените статью