What is Deque in Java?

A Deque (Double Ended Queue) in Java is a linear data structure that allows the insertion and deletion of elements from both the front and the rear ends. It can be used as a queue or a stack and enables efficient access to both ends of the collection.

Deque, Java Deque, Double Ended Queue, Java Collections, Data Structures
A Deque in Java allows for the addition or removal of elements from both ends, making it a versatile collection for various data manipulation tasks.

import java.util.ArrayDeque;

public class DequeExample {
    public static void main(String[] args) {
        ArrayDeque<Integer> deque = new ArrayDeque<>();
        
        // Adding elements to the front and rear
        deque.addFirst(1);
        deque.addLast(2);
        
        // Displaying elements
        System.out.println("Deque: " + deque);
        
        // Removing elements from the front and rear
        int front = deque.removeFirst();
        int rear = deque.removeLast();
        
        System.out.println("Removed from front: " + front);
        System.out.println("Removed from rear: " + rear);
        System.out.println("Deque after removals: " + deque);
    }
}
    

Deque Java Deque Double Ended Queue Java Collections Data Structures