What is the LinkedHashSet.containsAll in Java?

The LinkedHashSet is similar to the HashSet except that it maintains the insertion order of elements, whereas HashSet does not. Read more about. LinkedHashSet here.

The containsAll method will check if all the elements of the passed collection are present in the LinkedHashSet.

Syntax

boolean containsAll(Collection<?> c)

This method takes the collection to check if it is present in this set.

This method returns true if all the elements of the passed collection are present in the set.

If the passed argument is also a set, then the containsAll operation effectively modifies the set so that its value is the union of the two sets.

Code

import java.util.LinkedHashSet;
import java.util.ArrayList;
class containsAll {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(2);
list1.add(3);
System.out.println("The set is "+ set);
System.out.println("list1 is "+ list1);
System.out.println("If set contains list1 is "+ set.containsAll(list1));
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
list2.add(1);
System.out.println("list2 is "+ list2);
System.out.println("If set contains list2 is "+ set.containsAll(list2));
}
}

In the code above,

  • In line numbers 1 and 2: We import the LinkedHashSet and ArrayList class.

  • From line numbers 5 to 8: We create a new LinkedHashSet object with the name set and add three elements (1,2,3) to the set object using the add method.

  • From line numbers 10 to 12: We create a new ArrayList object with the name list and add two elements(2,3) to the list1 object using the add method.

  • In line number 16: We use the containsAll method to check if all elements of the list1 are present in the set. In this case, true is returned because all elements of list1 are present in the set.

  • From line numbers 18 to 20: We create a new ArrayList object with the name list2 and add two elements (5,1) to the list2 object using the add method.

  • In line number 23: We use the conainsAll method to check if all the elements of the list2 are present in the set. In this case, false is returned because element 5 of list2 is not present in the set.

Free Resources