×

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

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.