• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Collections – Deque Example in Java

December 24, 2014 by javainterviewpoint Leave a Comment

The java.util.Deque interface is a subtype of the java.util.Queue interface. In this type of queue, you can add and remove elements from both the ends and hence it is abbreviated as “Double Ended Queue” and pronounced as “deck” in short.

Lets see the basic operations using Dequeue

 Implementation

Since Deque is an interface,we need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Deque implementations of Java Collections.

  • java.util.LinkedList
  • java.util.ArrayDeque

Examples of creating Queue Instance

Queue queue1 = new LinkedList();
Queue queue2 = new ArrayDeque();

The order in which the elements are stored internally depends upon the type of implementation that we choose.

Adding elements to the queue

To add element  the deque we can use any of the below methods.

add() method inserts element to the head of the deque. This throws IllegalStateException” if no space is currently available. When using a capacity-restricted deque

addFirst() method also inserts element to the head of the deque. This throws IllegalStateException” if no space is currently available. When using a capacity-restricted deque

addLast() method to insert element to the tail of the deque. These method throws IllegalStateException” if no space is currently available. When using a capacity-restricted deque. These method returns a boolean, if the insertion is successful it will return “true” else it will return “false”.

Deque deque = new LinkedList();
deque.add("Java");
deque.addFirst("jQuery");
deque.addLast("HTML5");

Other way of adding element to the queue is through offer() method. All the method will throw IllegalStateException” if no space is currently available. When using a capacity-restricted deque

offer() method inserts element to the head of the deque.

offerFirst() method also inserts element to the head of the deque.

offerLast() method to insert element to the tail of the deque.

 

 deque.offer("AngualarJS");
 deque.offerFirst("NodeJS");
 deque.offerLast("Javascript");

Accessing elements of the queue

Elements of the queue can be accessed in two ways.

Using getFirst() method / getLast() method, This method returns the head/ tail element of the deque without removing from the queue. It throws “NoSuchElementException”  when the queue is empty.

deque.getFirst()
deque.getLast()

Using peekFirst()/peekLast() method, This method also returns the head/tail element of the deque without removing from the queue. It returns “null”  when the queue is empty.

deque.peekFirst()
deque.peekLast()

Removing elements from the queue

Using removeFirst()/pop() method, This method removes and returns the first element of the deque, will throw “NoSuchElementException”  when the queue is empty.

deque.removeFirst()
deque.pop()

Using removeLast() method, This method removes and returns the last element of the deque, will throw “NoSuchElementException”  when the queue is empty.

deque.removeLast()

Code Snippet

import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

public class DequeExample {

	public static void main(String[] args) 
	{
	    //Creating a queue object through LinkedList
		Deque deque = new LinkedList();
        
		//Adding elements to the deque
		deque.add("Java");
		//addFirst() adds the element to the head of the deque
		deque.addFirst("jQuery");
		//addFirst() adds the element to the tail of the deque
		deque.addLast("HTML5"); 
		
		//offer() adds the elements to the deque and returns a boolean
		deque.offer("AngualarJS");
		//offerFirst() adds the element to the head of the deque and returns a boolean
		deque.offerFirst("NodeJS");
		//offerFirst() adds the element to the tail of the deque and returns a boolean
		deque.offerLast("Javascript"); 
		
		System.out.println("Elements of the deque"+deque);
		
		//getFirst() Will retrive the head of the deque
		System.out.println("First element of the deque before removal:"+deque.getFirst());
		//The removeFirst() &pop() method will remove the first element of the queue
		deque.removeFirst();
		deque.pop();
		//peekFirst() Will retrive the head of the deque
		System.out.println("First element of the deque after removal:"+deque.peekFirst());
		
		//getLast() Will retrive the tail of the deque
		System.out.println("Last element of the deque before removal:"+deque.getLast());
		//The removeLast() method will remove the tail element of the queue
		deque.removeLast();
		//peekLast() Will retrive the tail of the deque
		System.out.println("Last element of the deque after removal:"+deque.peekLast());
		
		// Iterate through the queue elements.
        System.out.println("Normal Iteration");
        Iterator it1 = deque.iterator();
        while (it1.hasNext()) {
            System.out.println("    "+ it1.next());
        }
        
        // Reverse order iterator
        Iterator it2 = deque.descendingIterator();
        System.out.println("Reversed Iteration");
        while (it2.hasNext()) {
            System.out.println("    "+ it2.next());
        }
	}
}

Output

Elements of the deque[NodeJS, jQuery, Java, HTML5, AngualarJS, Javascript]
First element of the deque before removal:NodeJS
First element of the deque after removal:Java
Last element of the deque before removal:Javascript
Last element of the deque after removal:AngualarJS
Standard Iterator
    Java
    HTML5
    AngualarJS
Reverse Iterator
    AngualarJS
    HTML5
    Java

Other interesting articles which you may like …

  • How to use Java Collections Queue in Java
  • How to Reverse String in Java using String Tokenizer
  • How to remove an element from collection using Iterator Example
  • How to create read only List, Set, Map in Java?
  • How to Convert Array to ArrayList in Java?
  • Java ArrayList contains() Method Example
  • How to swap elements in an ArrayList
  • How to join two ArrayLists in java
  • Override toString() method of ArrayList in Java
  • Find Common Elements between two ArrayList in Java
  • Java ArrayList indexOf(Object o) Method Example
  • Java TreeMap values() Method Example
  • Java TreeMap floorKey() Method Example
  • Java HashMap putAll() Example
  • Java HashMap entrySet() Example
  • Java HashMap containsValue(Object value) Example
  • Java TreeSet descendingSet() Method Example
  • Java Vector toString() Example
  • Java Vector size() Example
  • Java LinkedHashSet add(E e) Method Example
  • Java LinkedList add(E e) Method Example

Filed Under: Collections, Deque, Java Tagged With: Deque, Deque Example in Java, Java Collections, java.util.Deque

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·