Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
removeall
java
communitycreator

What is Stack.removeAll in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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 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.

RELATED TAGS

stack
removeall
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring