Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
deque
interafce

How to use a Java deque

Educative Answers Team

Java deque is a two ended queue where elements can be added or removed from either ends. It is implemented by using the java.util.Deque interface which is also a subtype of the java.util.Queue interface.

This means that you can use Java deque like a Java queue if ever needed.

svg viewer

How to insert or remove queue elements

1 of 6

How to add an element in Deque

java.util.Deque provides 3 different functions for adding an element to a queue:

  • d.add(ElementToBeAdded): It adds an element to a queue at first available position from the start of the queue.

  • d.addFirst(ElementToBeAdded): It adds an element to the start of a queue and shifts all the existing elements to the right by one position.

  • d.addLast(ElementToBeAdded): It adds an element to the end of a queue.


Example

This example adds elements using the functions mentioned above and then prints the queue.

import java.util.*; 
class example { 
   public static void main(String[] args) { 
      Deque<String> d = new LinkedList<String>(); 
      d.add("10");
      d.addFirst("5"); 
      d.addLast("15"); 
      System.out.println("My deque is: " + d); 
   }
}

How to remove an element from Deque:

java.util.Deque provides 3 different functions for removing an element from a queue:

  • d.remove(): It simply removes an element from the start of a queue.

  • d.removeFirst(): This also removes an element from the start of a queue.

  • d.removeLast(): It removes an element from the end of a queue.


Example

This example adds elements using Example 1’s functions and then removes an element using the d.removeLast() and d.removeFirst() functions. You may replace d.removeFirst with d.remove() to verify the results.

import java.util.*; 
class example { 
   public static void main(String[] args) { 
      Deque<String> d = new LinkedList<String>(); 
      d.add("10");
      d.addFirst("5"); 
      d.addLast("15"); 
      System.out.println("My deque is: " + d); 

      d.removeLast(); 
      System.out.println("My deque after removing last element is: " + d);    

      d.removeFirst(); 
      System.out.println("My deque after removing first element is: " + d);          
   }
}

RELATED TAGS

java
deque
interafce
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring