The Wayback Machine - https://web.archive.org/web/20241127231556/https://www.geeksforgeeks.org/deque-interface-java-example/
Open In App

Deque interface in Java with Example

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Deque Interface present in java.util package is a subtype of the queue interface. The Deque is related to the double-ended queue that supports adding or removing elements from either end of the data structure. It can either be used as a queue(first-in-first-out/FIFO) or as a stack(last-in-first-out/LIFO). Deque is the acronym for double-ended queue.

  • Null Handling: Most implementations do not allow null elements, as null is used as a special return value to indicate the absence of elements.
  • Thread-Safe Alternatives: Use ConcurrentLinkedDeque or LinkedBlockingDeque for thread-safe operations and avoid ArrayDeque in concurrent environments as it is not thread-safe.

Example :

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

public class Example 
{
    public static void main(String[] args)
    {

        // Create a Deque of Strings
        Deque<String> deque = new ArrayDeque<>();

        deque.addFirst(1);
        deque.addLast(2);

        int first = deque.removeFirst();
        int last = deque.removeLast();

        // Displaying the Deque
        System.out.println("First: " + first + ", Last: " + last);
    }
}

Output
Deque elements: []


Hierarchy Diagram of Queue and Deque Interface in Java

Below is the hierarchy diagram of Queue Interface, where Deque Interface extends the Queue Interface. Go through the below diagram to know high level ideas on Deque Interface.

Queue and Deque Interface In Java


Syntax: The deque interface is declared as,

public interface Deque extends Queue

Creating Deque Objects

Since Deque is an interface, objects cannot be created of the type deque. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Deque. This type-safe queue can be defined as:

// Obj is the type of the object to be stored in Deque Deque<Obj> deque = new ArrayDeque<Obj> ();

Example: Deque

Java
// Java program to demonstrate the working
// of a Deque in Java

import java.util.*;

public class DequeExample {
    public static void main(String[] args)
    {
        Deque<String> deque
            = new LinkedList<String>();

        // We can add elements to the queue
        // in various ways

        // Add at the last
        deque.add("Element 1 (Tail)");

        // Add at the first
        deque.addFirst("Element 2 (Head)");

        // Add at the last
        deque.addLast("Element 3 (Tail)");

        // Add at the first
        deque.push("Element 4 (Head)");

        // Add at the last
        deque.offer("Element 5 (Tail)");

        // Add at the first
        deque.offerFirst("Element 6 (Head)");

        System.out.println(deque + "\n");

        // We can remove the first element
        // or the last element.
        deque.removeFirst();
        deque.removeLast();
        System.out.println("Deque after removing "
                        + "first and last: "
                        + deque);
    }
}

Output
[Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail)]

Deque after removing first and last: [Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail)]


Operations Using the Deque Interface and the ArrayDeque Class

Let’s see how to perform a few frequently used operations on the deque using the ArrayDeque class. 

1. Adding Elements:

In order to add an element in a deque, we can use the add() method. The difference between a queue and a deque is that in deque, the addition is possible from any direction. Therefore, there are other two methods available named addFirst() and addLast() which are used to add the elements at either end. 

Java
// Java program to demonstrate the
// addition of elements in deque

import java.util.*;
public class ArrayDequeDemo {
    public static void main(String[] args)
    {
        // Initializing an deque
        Deque<String> dq
            = new ArrayDeque<String>();

        // add() method to insert
        dq.add("For");
        dq.addFirst("Geeks");
        dq.addLast("Geeks");

        System.out.println(dq);
    }
}

Output
[Geeks, For, Geeks]


2. Removing Elements:

In order to remove an element from a deque, there are various methods available. Since we can also remove from both ends, the deque interface provides us with removeFirst(), removeLast() methods. Apart from that, this interface also provides us with the poll(), pop(), pollFirst(), pollLast() methods where pop() is used to remove and return the head of the deque. However, poll() is used because this offers the same functionality as pop() and doesn’t return an exception when the deque is empty. 

Java
// Java program to demonstrate the
// removal of elements in deque
import java.util.*;

public class ArrayDequeDemo {
  
    public static void main(String[] args)
    {
        // Initializing an deque
        Deque<String> dq = new ArrayDeque<String>();

        // add() method to insert
        dq.add("For");
        dq.addFirst("Geeks");
        dq.addLast("Geeks");

        System.out.println(dq);
      
        System.out.println(dq.pop());
      
        System.out.println(dq.poll());
      
        System.out.println(dq.pollFirst());
      
        System.out.println(dq.pollLast());
    }
}

Output
[Geeks, For, Geeks]
Geeks
For
Geeks
null


3. Iterating through the Deque:

Since a deque can be iterated from both directions, the iterator method of the deque interface provides us two ways to iterate. One from the first and the other from the back. 

Java
// Java program to demonstrate the
// iteration of elements in deque

import java.util.*;
public class ArrayDequeDemo {
    public static void main(String[] args)
    {
        // Initializing an deque
        Deque<String> dq
            = new ArrayDeque<String>();

        // add() method to insert
        dq.add("For");
        dq.addFirst("Geeks");
        dq.addLast("Geeks");
        dq.add("is so good");

        for (Iterator itr = dq.iterator();
            itr.hasNext();) {
            System.out.print(itr.next() + " ");
        }

        System.out.println();

        for (Iterator itr = dq.descendingIterator();
            itr.hasNext();) {
            System.out.print(itr.next() + " ");
        }
    }
}

Output
Geeks For Geeks is so good 
is so good Geeks For Geeks 

Note: The class which implements the Deque interface is ArrayDeque. 

ArrayDeque

ArrayDeque class which is implemented in the collection framework provides us with a way to apply resizable-array. This is a special kind of array that grows and allows users to add or remove an element from both sides of the queue. Array deques have no capacity restrictions and they grow as necessary to support usage. They are not thread-safe which means that in the absence of external synchronization, ArrayDeque does not support concurrent access by multiple threads. ArrayDeque class is likely to be faster than Stack when used as a stack. ArrayDeque class is likely to be faster than LinkedList when used as a queue. Let’s see how to create a queue object using this class. 

Java
// Java program to demonstrate the
// creation of deque object using the
// ArrayDeque class in Java

import java.util.*;

public class ArrayDequeDemo {
  
    public static void main(String[] args)
    {
        // Initializing an deque
        Deque<Integer> de_que = new ArrayDeque<Integer>(10);

        // add() method to insert
        de_que.add(10);
        de_que.add(20);
        de_que.add(30);
        de_que.add(40);
        de_que.add(50);

        System.out.println(de_que);

        // clear() method
        de_que.clear();

        // addFirst() method to insert the
        // elements at the head
        de_que.addFirst(564);
        de_que.addFirst(291);

        // addLast() method to insert the
        // elements at the tail
        de_que.addLast(24);
        de_que.addLast(14);

        System.out.println(de_que);
    }
}

Output
[10, 20, 30, 40, 50]
[291, 564, 24, 14]


Methods of Deque Interface

The following are the methods present in the deque interface:  

MethodDescription
add(element)This method is used to add an element at the tail of the queue. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion.
addFirst(element)This method is used to add an element at the head of the queue. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion.
addLast(element)This method is used to add an element at the tail of the queue. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion.
contains()This method is used to check whether the queue contains the given object or not.
descendingIterator()This method returns an iterator for the deque. The elements will be returned in order from last(tail) to first(head).
element()This method is used to retrieve, but not remove, the head of the queue represented by this deque.
getFirst()This method is used to retrieve, but not remove, the first element of this deque.
getLast()This method is used to retrieve, but not remove, the last element of this deque.
iterator()This method returns an iterator for the deque. The elements will be returned in order from first (head) to last (tail).
offer(element)This method is used to add an element at the tail of the queue. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false.
offerFirst(element)This method is used to add an element at the head of the queue. This method is preferable to addFirst() method since this method does not throws an exception when the capacity of the container is full since it returns false.
offerLast(element)This method is used to add an element at the tail of the queue. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false.
peek()This method is used to retrieve the element at the head of the deque but doesn’t remove the element from the deque. This method returns null if the deque is empty.
peekFirst()This method is used to retrieve the element at the head of the deque but doesn’t remove the element from the deque. This method returns null if the deque is empty.
peekLast()This method is used to retrieve the element at the tail of the deque but doesn’t remove the element from the deque. This method returns null if the deque is empty.
poll()This method is used to retrieve and remove the element at the head of the deque. This method returns null if the deque is empty.
pollFirst()This method is used to retrieve and remove the element at the head of the deque. This method returns null if the deque is empty.
pollLast()This method is used to retrieve and remove the element at the tail of the deque. This method returns null if the deque is empty.
pop()This method is used to remove an element from the head and return it.
push(element)This method is used to add an element at the head of the queue.
removeFirst()This method is used to remove an element from the head of the queue.
removeLast()This method is used to remove an element from the tail of the queue.
size()This method is used to find and return the size of the deque.

Advantages of Using Deque

  • Double-Ended: The main advantage of the Deque interface is that it provides a double-ended queue, which allows elements to be added and removed from both ends of the queue. This makes it a good choice for scenarios where you need to insert or remove elements at both the front and end of the queue.
  • Flexibility: The Deque interface provides a number of methods for adding, removing, and retrieving elements from both ends of the queue, giving you a great deal of flexibility in how you use it.
  • Blocking Operations: The Deque interface provides blocking methods, such as takeFirst and takeLast, that allow you to wait for elements to become available or for space to become available in the queue. This makes it a good choice for concurrent and multithreaded applications.

Disadvantages of Using Deque

  • Performance: The performance of a Deque can be slower than other data structures, such as a linked list or an array, because it provides more functionality.
  • Implementation Dependent: The behavior of a Deque can depend on the implementation you use. For example, some implementations may provide thread-safe operations, while others may not. It’s important to choose an appropriate implementation and understand its behavior before using a Deque.

Reference Book:

“Java Generics and Collections” by Maurice Naftalin and Philip Wadler is a comprehensive guide to the Java Collections Framework and generics, including the Deque interface. This book covers the basics of the Collections Framework, explains how to use collections and generics in practice, and provides tips and best practices for writing correct and efficient code. If you’re looking to learn more about the Deque interface and the Java Collections Framework in general, this book is an excellent resource.




Similar Reads

deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
deque::clear() and deque::erase() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::clear() The clear()
5 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Deque::front() and deque::back() in C++ STL
Deque or Double Ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed in the deque. deque::front()fron
4 min read
Why to Use Comparator Interface Rather than Comparable Interface in Java?
In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some reasons why you might want to use the Comparator i
9 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an object of DoubleToIntFunction type is used to define
1 min read
Java 8 | ObjLongConsumer Interface with Example
The ObjLongConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments and produces a result. However these kind of functions don't return any value. Hence this functional interface takes in one generic namel
2 min read
Java 8 | ObjIntConsumer Interface with Example
The ObjIntConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments and produces a result. However these kind of functions don't return any value. Hence this functional interface takes in one generic namely
2 min read
Java 8 | ObjDoubleConsumer Interface with Example
The ObjDoubleConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in two arguments and produces a result. However these kind of functions don't return any value. Hence this functional interface takes in one generic nam
2 min read
NavigableMap Interface in Java with Example
The NavigableMap interface is a member of the Java Collection Framework. It belongs to java.util package and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey, and along with this popular navigation method. It also provide ways to create a Sub Map from existing Map in Java
11 min read
Map.Entry interface in Java with example
Map.Entry interface in Java provides certain methods to access the entry in the Map. By gaining access to the entry of the Map we can easily manipulate them. Map.Entry is a generic and is defined in the java.util package. Declaration : Interface Map.Entry k -> Key V -> Value Methods: equals (Object o) - It compares the object (invoking object
4 min read
Java Native Interface with Example
In the Programming World, it is often seen in the comparison of Java vs C/C++. Although the comparison doesn't make any such sense, as both the languages have their Pros and Cons, but what if we can use multiple languages in a single Program? In this article, we will learn How to use JNI(Java Native Interface) to run multiple languages in a single
4 min read
Spring - RowMapper Interface with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
6 min read
Deque offerFirst() method in Java
The offerFirst(E e) method of Deque Interface inserts the specified element into the front of the Deque if it is possible to do so immediately without violating capacity restrictions. This method is preferable to addFirst() method since this method does not throws an exception when the capacity of the container is full since it returns false. Synta
3 min read
Deque addLast() method in Java
The addLast(E e) method of Deque Interface inserts the element passed in the parameter to the end of the Deque if there is space. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion. Syntax: boolean addLast(E e) Parameters: This method accepts
4 min read
Deque addFirst() method in Java with Examples
The addFirst(E e) method of Deque Interface inserts the element passed in the parameter to the front of the Deque if there is space. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion. Syntax: void addFirst(E e) Parameters: This method accept
4 min read
Deque offerLast() method in Java
The offerLast(E e) method of Deque Interface inserts the specified element into the end of the Deque if it is possible to do so immediately without violating capacity restrictions. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false. Syntax: boole
5 min read
Deque offer() method in Java
The offer(E e) method of Deque Interface inserts the specified element into this Deque if it is possible to do so immediately without violating capacity restrictions. This method is preferable to add() method since this method does not throws an exception when the capacity of the container is full since it returns false. Syntax: boolean offer(E e)
5 min read
Deque iterator() method in Java
The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator. Syntax: Iterator iterator() Parameters: This method does not accepts any parameter. Returns: This method
3 min read
Deque getLast() method in Java
The getLast() method of Deque Interface returns the last element or the tail of the Deque. It does not deletes the element. It throws an exception when the Deque is empty. Syntax: E getLast() Parameters: This method does not accepts any parameter. Returns: This method returns the last element or the tail of the Deque but does not delete it. Excepti
3 min read
Deque element() method in Java
The element() method of Deque Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the Deque. The method throws an exception when the Deque is empty. Syntax: E element() Parameters: This method does not accepts any parameter.Returns: This method returns the eleme
3 min read
Deque descendingIterator() method in Java
The descendingIterator(E e) method of Deque Interface returns an iterator over the elements in this deque in a reverse sequential order. The elements will be returned in order from last(tail) to first(head). The returned iterator is a “weakly consistent” iterator. Syntax: Iterator descendingIterator() Parameters: This method does not accept any par
4 min read
Deque contains() method in Java
The contains(E e) method of Deque Interface check for the presence of the element e in the Deque container. If the Deque contains one occurrence of the element, then it returns true else it returns false. Syntax: boolean contains(Object o) Parameters: This method accepts a mandatory parameter o which is the element that needs to be tested if it is
5 min read
Deque add() method in Java
The add(E e) method of Deque Interface inserts the element passed in the parameter to the end of the Deque if there is space. If the Deque is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion. Syntax: boolean add(E e) Parameters: This method accepts a manda
4 min read
Deque getFirst() method in Java
The getFirst() method of Deque Interface returns the first element or the head of the Deque. It does not deletes the element. It throws an exception when the Deque is empty. Syntax: E getFirst() Parameters: This method does not accepts any parameter.Returns: This method returns the first element or the head of the Deque but does not delete it.Excep
3 min read
Java 8 | IntToDoubleFunction Interface in Java with Examples
The IntToDoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in an int-valued argument and gives a double-valued result. The lambda expression assigned to an object of IntToDoubleFunction type is used to define
1 min read
Java 8 | DoubleToLongFunction Interface in Java with Examples
The DoubleToLongFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an long-valued result. The lambda expression assigned to an object of DoubleToLongFunction type is used to defi
1 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate<T, V> interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate<T, V> Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Practice Tags :
three90RightbarBannerImg