What is the Stack.containsAll method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The containsAll() method checks if all of the elements of the specific collection object are present in the Stack object.
Syntax
public boolean containsAll(Collection<?> c)
Argument
The collection to be checked for in the Stack is passed as an argument.
Return Value
containsAll() returns true if all of the elements of the passed collection are present in the Stack.
Code
import java.util.Stack;import java.util.ArrayList;class containsAll {public static void main( String args[] ) {Stack<Integer> stack = new Stack<>();stack.add(1);stack.add(2);stack.add(3);ArrayList<Integer> list1 = new ArrayList<>();list1.add(1);list1.add(3);System.out.println("The stack is "+ stack);System.out.println("\nlist1 is "+ list1);System.out.println("If stack contains all elements of list1 : "+ stack.containsAll(list1));ArrayList<Integer> list2 = new ArrayList<>();list2.add(4);System.out.println("\nlist2 is "+ list2);System.out.println("If stack contains all elements of list2 : "+ stack.containsAll(list2));}}
Explanation
In the code above:
-
In lines 1 and 2: We import the
StackandArrayListclasses. -
In line 4: We create an object for the
Stackclass with the namestack. -
In lines 6 to 8: We add three elements (
1,2,3) to the createdstackobject. -
In line 10: We create a new
ArrayListobject with the namelist1and add the elements1,3to it. -
In line 16: We call the
containsAll()method to check if all elements oflist1are present in thestack. In this case, the method returnstruebecause all the elements oflist1(1,3) are present in thestack. -
In line 18: We create a new
ArrayListobject with the namelist2and add the element4to it. -
In line 22: We call the
conainsAll()method again to check if all elements oflist2are present in thestack. In this case, the method returnsfalsebecause element4oflist2is not present in thestack.