What is Stack.removeAll 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 removeAll method will remove all the elements of the passed collection from the Stack if present.
Syntax
boolean removeAll(Collection<?> c)
This method takes the collection object to be removed from the stack as an argument.
This method returns true if the stack changed as a result of the call (any one of the elements from the Collection is present and removed from the stack). Otherwise, false will be returned.
Code
import java.util.Stack;import java.util.ArrayList;class RemoveAll {public static void main( String args[] ) {Stack<Integer> stack = new Stack<>();stack.push(1);stack.push(2);stack.push(3);ArrayList<Integer> list = new ArrayList<>();list.add(1);list.add(4);System.out.println("The stack is "+ stack);System.out.println("The list is "+ list);System.out.println("\nCalling stack.removeAll(list). Is stack changed - " + stack.removeAll(list));System.out.println("\nThe stack is "+ stack);}}
In the above code:
-
In line number 1 and 2: We imported the
StackandArrayListclass. -
From line number 5 to 8: We created a new
Stackobject with the namestackand added three elements (1,2,3) to thestackobject using thepushmethod. -
From line number 9 to 11: We created a new
ArrayListobject with the namelistand Added two elements (1,4) to thelistobject using theaddmethod. -
In line number 15: We used the
removeAllmethod to remove all the elements of thelistfrom thestack. The element1in the list is present in thestack, so it is removed. The element4is not present in thestack, so it is not removed. After calling theremoveAllmethod, the content of thestackobject changes, sotrueis returned.