Java - Double Ended Queues

Introduction

A doubly ended queue or deque allows insertion and removal of elements from both ends (the head and the tail).

Deque represents a doubly ended queue.

It is pronounced "deck," not "de queue."

ArrayDeque and LinkedList classes implements the Deque interface.

The ArrayDeque class is backed by an array whereas the LinkedList class is backed by a linked list.

The following code uses a Deque as a FIFO queue.

Demo

import java.util.Deque;
import java.util.LinkedList;
import java.util.NoSuchElementException;

public class Main {
  public static void main(String[] args) {
    // Create a Deque and add elements at its tail using
    // addLast() or offerLast() method
    Deque<String> deque = new LinkedList<>();
    deque.addLast("XML");
    deque.offerLast("Javascript");
    deque.offerLast("Json");
    deque.offerLast("Java");

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

    // Let's remove elements from the Deque until it is empty
    while (deque.peekFirst() != null) {
      System.out.println("Head Element: " + deque.peekFirst());
      deque.removeFirst();/* w ww. ja  v a 2 s.  c o m*/
      System.out.println("Removed one element from Deque");
      System.out.println("Deque: " + deque);
    }

    // Now, the Deque is empty. Try to call its peekFirst(),
    // getFirst(), pollFirst() and removeFirst() methods
    System.out.println("deque.isEmpty(): " + deque.isEmpty());

    System.out.println("deque.peekFirst(): " + deque.peekFirst());
    System.out.println("deque.pollFirst(): " + deque.pollFirst());

    try {
      String str = deque.getFirst();
      System.out.println("deque.getFirst(): " + str);
    } catch (NoSuchElementException e) {
      System.out.println("deque.getFirst(): Deque is empty.");
    }

    try {
      String str = deque.removeFirst();
      System.out.println("deque.removeFirst(): " + str);
    } catch (NoSuchElementException e) {
      System.out.println("deque.removeFirst(): Deque is empty.");
    }
  }
}

Result

Related Topics