Java - Use a Deque as a stack or LIFO queue

Description

Use a Deque as a stack or LIFO queue

Demo

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
  public static void main(String[] args) {
    // Create a Deque and use it as stack
    Deque<String> deque = new ArrayDeque<>();
    deque.push("XML");
    deque.push("Javascript");
    deque.push("Json");
    deque.push("Java");

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

    // Let's remove all elements from the Deque
    while (deque.peek() != null) {
      System.out.println("Element at top: " + deque.peek());
      System.out.println("Popped: " + deque.pop());
      System.out.println("Stack: " + deque);
    }/*from   w w w . jav  a 2 s  . co  m*/

    System.out.println("Stack is empty: " + deque.isEmpty());
  }
}

Result

Related Topic