What is the Stack.iterator() 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 iterator method will return an iterator for the elements of the Stack object.
Syntax
public Iterator<E> iterator()
Here, E represents the type of the iterator.
This method doesn’t take any argument.
It returns an iterator for the elements of the Stack. In the returned iterator, the elements are returned from index 0.
Code
The following code illustrates the use of the Stack.iterator() method.
import java.util.Stack;import java.util.Iterator;class IteratorExample {public static void main( String args[] ) {// creating a Stack objectStack<Integer> stack = new Stack<>();//pushing elements into the stackstack.push(1);stack.push(2);stack.push(3);stack.push(4);// creating an iteratorIterator<Integer> itr = stack.iterator();// displaying stack elements using iteratorSystem.out.println("The elements of the stack are:");while(itr.hasNext()) {System.out.print(itr.next() + "\n");}}}
In the above code, we take the following steps:
-
In line number 1: We import the
Stackclass. -
In line number 6: We create a new
Stackobject with the namestack. -
From line number 9 to 12: We add four elements (
1,2,3,4) to thestackobject using thepushmethod. -
In line number 15: We use the
iteratormethod to get aniteratorfor the elements of thestack. -
Then, we print the elements of the iterator using the
whileloop. We use thehasNextmethod of the iterator object to check if the iterator contains more elements, then use thenextmethod to get the next available element in the iterator.