Iterating over a Stack Example

This example shows various ways of iterating over a Stack.
  • Iterate over a Stack using Java 8 forEach().
  • Iterate over a Stack using iterator().
  • Iterate over a Stack using iterator() and Java 8 forEachRemaining() method.
  • Iterate over a Stack from Top to Bottom using listIterator().

Iterating over a Stack Example

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;

public class StackIterationExample {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("John");
        stack.push("Doe");
        stack.push("Jane");
        stack.push("Smith");

        // 1. Iterate over a Stack using Java 8 forEach()
        System.out.println("Using Java 8 forEach():");
        stack.forEach(System.out::println);

        System.out.println("\nUsing iterator():");
        // 2. Iterate over a Stack using iterator()
        Iterator<String> iterator = stack.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        System.out.println("\nUsing iterator() and Java 8 forEachRemaining() method:");
        // 3. Iterate over a Stack using iterator() and Java 8 forEachRemaining() method
        Iterator<String> forEachRemainingIterator = stack.iterator();
        forEachRemainingIterator.forEachRemaining(System.out::println);

        System.out.println("\nIterating from Top to Bottom using listIterator():");
        // 4. Iterate over a Stack from Top to Bottom using listIterator()
        ListIterator<String> listIterator = stack.listIterator(stack.size());
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}
Output:
Using Java 8 forEach():
John
Doe
Jane
Smith

Using iterator():
John
Doe
Jane
Smith

Using iterator() and Java 8 forEachRemaining() method:
John
Doe
Jane
Smith

Iterating from Top to Bottom using listIterator():
Smith
Jane
Doe
John
In this example: 
The forEach() method introduced in Java 8 is used directly on the Stack object. 

The conventional iterator() method is used to obtain an iterator that allows iteration from the bottom to the top of the stack. 

The forEachRemaining() method is a Java 8 enhancement to the Iterator interface, which allows you to perform an action for each remaining element until all elements have been processed. 

The listIterator() method is used with an initial index argument to obtain a ListIterator positioned at the top of the stack. 

The hasPrevious() and previous() methods are then used to iterate from the top to the bottom of the stack.

Comments