The
Stack
class 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.
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.
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 Stack
and ArrayList
class.
From line number 5 to 8: We created a new Stack
object with the name stack
and added three elements (1,2,3
) to the stack
object using the push
method.
From line number 9 to 11: We created a new ArrayList
object with the name list
and Added two elements (1,4
) to the list
object using the add
method.
In line number 15: We used the removeAll
method to remove all the elements of the list
from the stack
. The element 1
in the list is present in the stack
, so it is removed. The element 4
is not present in the stack
, so it is not removed. After calling the removeAll
method, the content of the stack
object changes, so true
is returned.