What is the Stack.retainAll method in Java?

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 retainAll method removes all of the elements of the Stack object that are not present in the passed collection.

Syntax

boolean retainAll(Collection<?> c)

Parameters

This method takes the collection object to be retained in the Stack object as an argument.

Return value

retainAll returns true if the stack changes as a result of the call, i.e., any element is removed from the stack due to the element not being present in the Collection. Otherwise, the method returns false.

Code

import java.util.Stack;
import java.util.ArrayList;
class RetainAll {
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.retainAll(list). Is stack changed - " + stack.retainAll(list));
System.out.println("\nThe stack is "+ stack);
}
}

Explanation

In the code above, we:

  • Lines 1-2: Import the Stack and ArrayList classes.

  • Lines 5-8: Create a new Stack object with the name stack and use the push method to add three elements (1,2,3) to the stack object.

  • Lines 10-12: Create a new ArrayList object with the name list and use the add method to add two elements (1,4) to the list object.

  • Line 16: Use the retainAll method to only retain elements that are present in the list. In our case, the elements of the list and stack are as follows:

Elements of list -- 1,4
Elements of stack -- 1,2,3

The retainAll method will:

  • Check if element 1 of the stack is present in the list. The list contains 1, so 1 is retained in the stack.

  • Check if element 2 of the stack is present in the list. The list doesn’t contain 2, so the 2 is removed from the stack.

  • Check if element 3 of the stack is present in the list. The list doesn’t contain 3, so the 3 is removed from the stack.

The resulting stack will be [1].