×

Deque in Java

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.

import Java.util.*;
class DequeDemo
{
    public static void main(String[] args)
    {
        Deque<String> d = new LinkedList<String>();
        //adding elements to the queue using different ways
        d.add("Java"); // add to tail
        d.addFirst("Pyhton"); //add to head
        d.addLast("C#"); //add to tail
        d.push("CCNA"); //add to head
        d.offer("Jquery"); //add to tail
        d.offerFirst("HTML"); //add to head
        d.offerLast("CSS"); //add to tail
        //printing the deque
        System.out.println("Elements in the Deque is \n"+ d + "\n");  
        // displaying iterator in reverse order
        Iterator rev = d.descendingIterator();
        System.out.println("Iterator in Reverse Order:");
        while (rev.hasNext())
            System.out.println("\t" + rev.next());
        // Peek method returns the head, without deleting it from the deque
        System.out.println("Peek " + d.peek());
        System.out.println("After peek: " + d);
        // returning last element without removing
        System.out.println("PeekLast"+ d.peekLast());
        // Poll returns the head of the queue, and removes it from the deque
        System.out.println("Poll " + d.poll());
        System.out.println("After poll: " + d);
        //checking if a specific element exists in the deque
        System.out.println("Contains element 3: " + d.contains("Jquery"));
        //removing the first and last element.
        d.removeFirst();
        d.removeLast();
        System.out.println("Deque after removing first and last elements: " + d);
    }
} 

Output:

Elements in the Deque is
[HTML, CCNA, Pyhton, Java, C#, Jquery, CSS]
Iterator in Reverse Order:
       CSS
       Jquery
       C#
       Java
       Pyhton
       CCNA
       HTML
Peek HTML
After peek: [HTML, CCNA, Pyhton, Java, C#, Jquery, CSS]
PeekLastCSS
Poll HTML 

Related Topics

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary. Using toBinaryString() method Using user-defined logic Using Integer.toBinaryString() The toBinaryString() is a static method of Integer...

2 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.