What is the Stack.retainAll 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 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
StackandArrayListclasses. -
Lines 5-8: Create a new
Stackobject with the namestackand use thepushmethod to add three elements (1,2,3) to thestackobject. -
Lines 10-12: Create a new
ArrayListobject with the namelistand use theaddmethod to add two elements (1,4) to thelistobject. -
Line 16: Use the
retainAllmethod to only retain elements that are present in thelist. In our case, the elements of thelistandstackare as follows:
Elements of list -- 1,4
Elements of stack -- 1,2,3
The retainAll method will:
-
Check if element
1of thestackis present in thelist. Thelistcontains1, so1is retained in thestack. -
Check if element
2of thestackis present in thelist. Thelistdoesn’t contain2, so the2is removed from thestack. -
Check if element
3of thestackis present in thelist. Thelistdoesn’t contain3, so the3is removed from thestack.
The resulting stack will be [1].