What is the Stack.iterator() 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 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 object
Stack<Integer> stack = new Stack<>();
//pushing elements into the stack
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
// creating an iterator
Iterator<Integer> itr = stack.iterator();
// displaying stack elements using iterator
System.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 Stack class.

  • In line number 6: We create a new Stack object with the name stack.

  • From line number 9 to 12: We add four elements (1,2,3,4) to the stack object using the push method.

  • In line number 15: We use the iterator method to get an iterator for the elements of the stack.

  • Then, we print the elements of the iterator using the while loop. We use the hasNext method of the iterator object to check if the iterator contains more elements, then use the next method to get the next available element in the iterator.

Free Resources