Stack iterator() method in Java with Example


The iterator() method in Java is used to return an iterator over the elements in the stack. The iterator can be used to traverse the stack in either direction.

Syntax:

public Iterator<E> iterator()

Here, E is the type of elements in the stack.

Example:

import java.util.*;

public class StackIteratorExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);
        stack.push(50);

        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}

Output:

50 40 30 20 10

In the above example, we have created a stack of integers and added some elements to it. Then, we have obtained an iterator using the iterator() method and used it to traverse the stack in reverse order. The hasNext() method is used to check if there are more elements in the stack and the next() method is used to retrieve the next element in the stack.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.