Deque Interface

5. Deque Interface

The Deque is belong to the double-ended queue that supports addition or removal of elements from either of any end of the deque, we can use it as a queue (first-in-first-out/FIFO) or as a stack (last-in-first-out/LIFO). Below are few methods declared in the Deque interface. They are as follows:

Method Role
public boolean add(element) Add the given element into the tail.
public void addFirst(element) Add the given element into the head.
public void addLast(element) Add the given element into the tail.
public boolean offer(element) Adds an element to the tail and returns a boolean to define if the insertion was successful.
public boolean offerFirst(element) Adds an element to the head and returns a boolean to define if the insertion was successful.
public boolean offerLast(element)  Adds an element to the tail and returns a boolean to define if the insertion was successful.
public Iterator iterator() Returns an iterator.
public Iterator descendingIterator() Returns an iterator that has the reverse order for this deque.
public void push(element)  Adds an element to the head.
public E pop(element) Removes an element from the head and returns it.
public E removeFirst()  Removes the element at the head.
public E removeLast() Removes the element at the tail.

Let us see an example:

package collectionFramework;

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;

public class DequeTest {

  public static void main(String[] args) {
    Deque deque = new LinkedList<>();
    deque.add("test element 1"); // Add element at tail
    deque.addFirst("test element 2"); // Add element at head
    deque.addLast("test element 3"); // Add element at tail
    deque.push("test element 4"); // Add element at head
    deque.offer("test element 5"); // Add element at tail
    deque.offerFirst("test element 6"); // Add element at head
    deque.offerLast("test element 7");	// Add element at tail

    // Traverse in forward direction
    Iterator iterator = deque.iterator();
    System.out.println("Traverse in forward direction");
    while (iterator.hasNext())
      System.out.println(iterator.next());

    // Traverse in reverse direction
    Iterator reverse = deque.descendingIterator();
    System.out.println("Traverse in reverse direction");
    while (reverse.hasNext())
      System.out.println(reverse.next());

  }
}

Output:

Traverse in forward direction
test element 6
test element 4
test element 2
test element 1
test element 3
test element 5
test element 7
Traverse in reverse direction
test element 7
test element 5
test element 3
test element 1
test element 2
test element 4
test element 6