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
containsAlloperation effectively modifies the set so that its value is theunionof 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
LinkedHashSetandArrayListclass. -
From line numbers 5 to 8: We create a new
LinkedHashSetobject with the namesetand add three elements (1,2,3) to thesetobject using theaddmethod. -
From line numbers 10 to 12: We create a new
ArrayListobject with the namelistand add two elements(2,3) to thelist1object using theaddmethod. -
In line number 16: We use the
containsAllmethod to check if all elements of thelist1are present in theset. In this case,trueis returned because all elements oflist1are present in theset. -
From line numbers 18 to 20: We create a new
ArrayListobject with the namelist2and add two elements (5,1) to thelist2object using theaddmethod. -
In line number 23: We use the
conainsAllmethod to check if all the elements of thelist2are present in theset. In this case,falseis returned because element5oflist2is not present in theset.