This post will discuss various methods to iterate over Deque in Java.

A Deque is a linear collection that supports insertion and removal at both ends. All Deque implementations like ArrayDeque, LinkedList, etc., use “double ended queue”, which provides a more complete and consistent set of LIFO and FIFO operations.

 
We should use Deque in preference to the Stack class (see this). Following are few methods provided by the Deque interface to support stack operations:

  1. push(E e) Pushes the specified element at the head of this deque.
  2. E pop() Pops an element from the head of this deque. In other words, it removes and returns the first element of this deque.
  3. Iterator<E> iterator() Returns an iterator over the elements in this deque. The elements are returned from head to tail.

 
Similarly, the following are few methods provided by the Deque interface to support queue operations:

  1. boolean add(E e) Inserts the specified element at the tail of this deque.
  2. E remove() Retrieves and removes the head of this deque (in other words, the first element of this deque).
  3. Iterator<E> descendingIterator() Returns an iterator over the elements in this deque in reverse sequential order, i.e., the elements are returned from tail to head.

1. Using Iterator

We can use iterator() that returns an iterator to iterate over a deque in LIFO order, i.e., the elements will be traversed from head to tail, as shown below:

Download  Run Code

 
We can use descendingIterator() that returns an iterator to iterate over a deque in FIFO order, i.e., the elements will be traversed from tail to head, as shown below:

Download  Run Code

 
Please note that the iterator will throw a ConcurrentModificationException if the deque is modified after it is created except through the iterator’s own remove method.

2. Using enhanced for-loop

As Deque implements Iterable interface, we can use enhanced for-loop to loop through deque in LIFO order, as shown below:

Download  Run Code

3. Java 8 – Converting Deque to Streams

In Java 8 and above, we can loop a deque in LIFO order with the help of streams, lambdas, and forEach, as shown below:

Download  Run Code

4. Converting Deque to array

We can first convert the deque into an array using toArray() method and then print it using Arrays.toString() method. There are many implementations of toArray() method, as shown below:

Download Code

5. Converting Deque to Vector

The Enumeration interface provides methods to enumerate through the elements of a Vector. So, we can convert the deque into a vector and finally print all elements of that vector.

Download  Run Code

6. Converting Deque to String

If we’re only required to display contents of the deque, we can print the string representation of deque using the toString() method, as shown below:

Download  Run Code

That’s all about iterating over Deque in Java.