Queues and Deques in Java

Lesson Overview

Welcome to our exploration of queues and deques. These structures frequently surface in everyday programming, managing everything from system processes to printer queues. In this lesson, our goal is to understand and implement queues and deques in Java. Let's dive in!

Introduction to Queues

A queue, similar to waiting in line at a store, operates on the "First In, First Out" or FIFO principle. Java's LinkedList class enables the implementation of queues. This class includes methods such as add() for adding items and poll() for removing items.

import java.util.LinkedList;
import java.util.Queue;

// Create a queue and add items
Queue<String> q = new LinkedList<>();
q.add("Apple");
q.add("Banana");
q.add("Cherry");

// Remove an item
System.out.println(q.poll());  // Expects "Apple"

The dequeued item, "Apple", was the first item we inserted, demonstrating the FIFO principle of queues.

Practical Implementation of Queues

Before trying to remove items from our queue, let's ensure it is not empty. This precaution will prevent runtime errors when attempting to dequeue from an empty queue.

import java.util.LinkedList;
import java.util.Queue;

// Create a queue and enqueue items
Queue<String> q = new LinkedList<>();
q.add("Item 1");
q.add("Item 2");

// Check if the queue is non-empty, then dequeue an item
if (!q.isEmpty()) {
    System.out.println(q.poll());  // Expects "Item 1"
}

Introduction to Deques

A deque, or "double-ended queue," allows the addition and removal of items from both ends. Java provides the ArrayDeque class for implementing deques. We can add items to both ends of our deque using the addLast(item) method for the right end and the addFirst(item) method for the left. Similarly, we can remove elements from left and right ends using removeFirst and removeLast.

import java.util.ArrayDeque;
import java.util.Deque;

// Create a deque and add items
Deque<String> d = new ArrayDeque<>();
d.addLast("Middle");
d.addLast("Right end");
d.addFirst("Left end");

// Remove an item
System.out.println(d.removeLast());  // Expects "Right end"

// Remove an item from the left
System.out.println(d.removeFirst()); // Expects "Left end"
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal