Deque in java collections with Example

Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the ends.

Deque in Java

Deque is also used as a queue or as a stack because it supports both First In First Out(FIFO) and Last In First Out(LIFO). And its performance is faster than the queue or stack.

Deque in Java collection

Deque provides the method to insert and delete the elements at both the ends. Each of the following methods is present in two forms; one throws an exception and other returns a value depending on the operation (either null or false).

  Elements at Head Elements at Tail
  Throws exception Special Value Throws exception Special Value
Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
Remove removeFirst() pollFirst() removeLast() pollLast()
Examine getFirst() peekFirst() getLast() peekLast

Deque method and its description:

Modifier and Data Type Methods Description
void addFirst(E e) It pushes the specified element at the head of the deque if it is possible to do so without violating capacity restrictions.
void addLast(E e) It pushes the specified element at the tail of the deque if it is possible to do so without violating capacity restrictions.
Iterator<E> descendingIterator() It results in an iterator over the elements in the deque in reverse sequential order.
E getFirst() It retrieves the element from the head of the queue, but it does not remove that element from the Deque.
E getLast() It retrieves the element from the tail of the queue, but it does not remove that element from the Deque.
boolean offerFirst(E e) It inserts the specified element at the head of the Deque unless it violates capacity restrictions.
boolean offerLast(E e) It inserts the specified element at the tail of the Deque unless it violates capacity restrictions.
E peekFirst() It retrieves the elements from the head of the Deque, but does not remove that element, or returns null if the Deque is empty.
E peekLast() It retrieves the elements from the tail of the Deque but does not remove that element, or it returns null if the deque is empty.
E pollFirst() It retrieves the element from the head of the Deque and also removes that element, or returns null if the Deque is empty.
E pollLast() It retrieves and removes the element from the tail of the Deque, or returns null if this Deque is empty.
E removeFirst() It retrieves as well as removes the element from the head of the Deque.
boolean removeFirstOccurrence() This removes the first occurrence of the argumented element from the Deque.
E removeLast() It retrieves and removes the element from the tail of the Deque.
boolean removeLastOccurance(Object o) This removes the last occurrence of the specified element from the Deque.

Below is an example showing the working of some methods in the Deque.

Output:

Pin It on Pinterest

Share This