Stack in Java

Spread the love

A Stack is a Last In First Out (LIFO) data structure. It supports two basic operations called push and pop. The push operation adds an element at the top of the stack, and the pop operation removes an element from the top of the stack.

Stack memory structure

Java provides a Stack class which models the Stack data structure. The Stack class is part of Java’s collections framework. Following is the class hierarchy of Stack in Java 

Stack Hierarchy in java

The Stack class extends Vector which implements the List interface. A Vector is a re-sizable collection. It grows its size to accommodate new elements and shrinks the size when the elements are removed.

Since the Stack class extends Vector, it also grows and shrinks its size as needed when new elements are added or removed.

Creating a Stack and Performing basic operations like push, pop and peek

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        // Creating a Stack
        Stack<String> stackOfCards = new Stack<>();

        // Pushing new items to the Stack
        stackOfCards.push("Jack");
        stackOfCards.push("Queen");
        stackOfCards.push("King");
        stackOfCards.push("Ace");

        System.out.println("Stack => " + stackOfCards);
        System.out.println();

        // Popping items from the Stack
        String cardAtTop = stackOfCards.pop();  // Throws EmptyStackException if the stack is empty
        System.out.println("Stack.pop() => " + cardAtTop);
        System.out.println("Current Stack => " + stackOfCards);
        System.out.println();

        // Get the item at the top of the stack without removing it
        cardAtTop = stackOfCards.peek();
        System.out.println("Stack.peek() => " + cardAtTop);
        System.out.println("Current Stack => " + stackOfCards);

    }
}
# Output
Stack => [Jack, Queen, King, Ace]

Stack.pop() => Ace
Current Stack => [Jack, Queen, King]

Stack.peek() => King
Current Stack => [Jack, Queen, King]

Universal Truth !

Data Structures have been a boon to the programming world as they simplify programming to a great extent.

Other Stack Operations

  • Check if the stack is empty.
  • Find the size of the stack.
  • Search for an element in the Stack.
import java.util.Stack;

public class StackSizeSearchExample {
    public static void main(String[] args) {
        Stack<String> stackOfCards = new Stack<>();

        stackOfCards.push("Jack");
        stackOfCards.push("Queen");
        stackOfCards.push("King");
        stackOfCards.push("Ace");

        System.out.println("Stack : " + stackOfCards);

        // Check if the Stack is empty
        System.out.println("Is Stack empty? : " + stackOfCards.isEmpty());

        // Find the size of Stack
        System.out.println("Size of Stack : " + stackOfCards.size());

        // Search for an element
        // The search() method returns the 1-based position of the element from the top of the stack
        // It returns -1 if the element was not found in the stack
        int position = stackOfCards.search("Queen");

        if(position != -1) {
            System.out.println("Found the element \"Queen\" at position : " + position);
        } else {
            System.out.println("Element not found");
        }

    }
}
# Output
Stack : [Jack, Queen, King, Ace]
Is Stack empty? : false
Size of Stack : 4
Found the element "Queen" at position : 3

Iterating over a Stack

The example in this section 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().
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Stack;

public class IterateOverStackExample {
    public static void main(String[] args) {
        Stack<String> stackOfPlates = new Stack<>();

        stackOfPlates.add("Plate 1");
        stackOfPlates.add("Plate 2");
        stackOfPlates.add("Plate 3");
        stackOfPlates.add("Plate 4");

        System.out.println("=== Iterate over a Stack using Java 8 forEach() method ===");
        stackOfPlates.forEach(plate -> {
            System.out.println(plate);
        });

        System.out.println("\n=== Iterate over a Stack using iterator() ===");
        Iterator<String> platesIterator = stackOfPlates.iterator();
        while (platesIterator.hasNext()) {
            String plate = platesIterator.next();
            System.out.println(plate);
        }

        System.out.println("\n=== Iterate over a Stack using iterator() and Java 8 forEachRemaining() method ===");
        platesIterator = stackOfPlates.iterator();
        while (platesIterator.hasNext()) {
            String plate = platesIterator.next();
            System.out.println(plate);
        }


        System.out.println("\n=== Iterate over a Stack from TOP to BOTTOM using listIterator() ===");
        // ListIterator allows you to traverse in both forward and backward directions.
        // We'll start from the top of the stack and traverse backwards.
        ListIterator<String> platesListIterator = stackOfPlates.listIterator(stackOfPlates.size());
        while (platesListIterator.hasPrevious()) {
            String plate = platesListIterator.previous();
            System.out.println(plate);
        }
    }
}
# Output
=== Iterate over a Stack using Java 8 forEach() method ===
Plate 1
Plate 2
Plate 3
Plate 4

=== Iterate over a Stack using iterator() ===
Plate 1
Plate 2
Plate 3
Plate 4

=== Iterate over a Stack using iterator() and Java 8 forEachRemaining() method ===
Plate 1
Plate 2
Plate 3
Plate 4

=== Iterate over a Stack from TOP to BOTTOM using listIterator() ===
Plate 4
Plate 3
Plate 2
Plate 1

Conclusion

In this article, you learned what is a Stack, how to create a Stack in Java, how to perform push and pop operations in a Stack, how to check if the Stack is empty, how to find the size of the Stack and how to search for an element in the Stack.

Thanks for reading. See you in the next post. This article is from callicoder

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” 
― Rick Cook, The Wizardry Compiled