|
| 1 | +import java.util.Iterator; |
| 2 | +import java.util.ListIterator; |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +public class IterateOverStackExample { |
| 6 | + public static void main(String[] args) { |
| 7 | + Stack<String> stackOfPlates = new Stack<>(); |
| 8 | + |
| 9 | + stackOfPlates.add("Plate 1"); |
| 10 | + stackOfPlates.add("Plate 2"); |
| 11 | + stackOfPlates.add("Plate 3"); |
| 12 | + stackOfPlates.add("Plate 4"); |
| 13 | + |
| 14 | + System.out.println("=== Iterate over a Stack using Java 8 forEach() method ==="); |
| 15 | + stackOfPlates.forEach(plate -> { |
| 16 | + System.out.println(plate); |
| 17 | + }); |
| 18 | + |
| 19 | + System.out.println("\n=== Iterate over a Stack using iterator() ==="); |
| 20 | + Iterator<String> platesIterator = stackOfPlates.iterator(); |
| 21 | + while (platesIterator.hasNext()) { |
| 22 | + String plate = platesIterator.next(); |
| 23 | + System.out.println(plate); |
| 24 | + } |
| 25 | + |
| 26 | + System.out.println("\n=== Iterate over a Stack using iterator() and Java 8 forEachRemaining() method ==="); |
| 27 | + platesIterator = stackOfPlates.iterator(); |
| 28 | + while (platesIterator.hasNext()) { |
| 29 | + String plate = platesIterator.next(); |
| 30 | + System.out.println(plate); |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + System.out.println("\n=== Iterate over a Stack from TOP to BOTTOM using listIterator() ==="); |
| 35 | + // ListIterator allows you to traverse in both forward and backward directions. |
| 36 | + // We'll start from the top of the stack and traverse backwards. |
| 37 | + ListIterator<String> platesListIterator = stackOfPlates.listIterator(stackOfPlates.size()); |
| 38 | + while (platesListIterator.hasPrevious()) { |
| 39 | + String plate = platesListIterator.previous(); |
| 40 | + System.out.println(plate); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments