A Hands-on Guide To The Java Queue Interface

July 21, 2023
A Hands On Guide to the Java Queue Interface



The Java Queue Interface works like a fast-food restaurant’s drive-thru following the first-in-first-out or FIFO principle. It enables developers to queue objects or elements in the queue and execute functions like deletion, insertion, and inspection orderly.

The queue interface performs this using implementation classes like LinkedList, PriorityQueue, ArrayBlockingQueue, DelayQueue, and PriorityBlockingQueue.

new java job roles

In this article, we’ll provide a hands-on guide to the Java Queue Interface and discuss its implementation with Java Queue examples. So, without further ado, let’s dive in.

How to Use Java Queue Interface?

So, it is established by now that the Java Queue Interface is a tool that enables us to represent a collection of objects or elements in a specified order. Now, we will describe how to use this feature for maximum impact.

Step 1 – Import the required package

import java.util.Queue;

import java.util.LinkedList;

Step 2 – Use LinkedList implementation to create an instance

Queue<Type> queue = new LinkedList<>();

*Type denotes the actual type of object or element to be stored in the queue.

Step 3 – Use add() or offer() method to add elements

queue.add(element); // Throws an exception if the operation fails

queue.offer(element); // Returns false if the operation fails

Step 4 – Use remove() or pull() to retrieve or remove objects from the queue

Type element = queue.remove(); // Throws an exception if the queue is empty

Type element = queue.poll(); // Returns null if the queue is empty

Step 5 – Use peek() method to retrieve without removing

Type element = queue.remove(); // Throws an exception if the queue is empty

Type element = queue.poll(); // Returns null if the queue is empty

Step 6 – Use isEmpty() method to check the queue storage

boolean isEmpty = queue.isEmpty();

Example of Java Queue Interface

import java.util.Queue;

import java.util.LinkedList;

public class QueueExample {

    public static void main(String[] args) {

        Queue<String> queue = new LinkedList<>();

        // Add elements to the queue

        queue.add("Apple");

        queue.add("Banana");

        queue.add("Orange");

        // Retrieve and remove elements from the queue

        String element = queue.remove();

        System.out.println("Removed: " + element);

        // Retrieve, but do not remove, the head of the queue

        String head = queue.peek();

        System.out.println("Head: " + head);

        // Check if the queue is empty

        boolean isEmpty = queue.isEmpty();

        System.out.println("Is empty: " + isEmpty);

    }

}

Output:

Removed: Apple

Head: Banana

Is empty: false

Java Queue Interface Implementation

Let’s now see some Java Queue Implementation examples to see the feature in action and its use.

LinkedList Example:

import java.util.LinkedList;

public class LinkedListExample {

    public static void main(String[] args) {

        // Create a LinkedList

        LinkedList<String> linkedList = new LinkedList<>();

        // Add elements to the LinkedList

        linkedList.add("Apple");

        linkedList.add("Banana");

        linkedList.add("Orange");

        // Print the LinkedList

        System.out.println("LinkedList: " + linkedList);

        // Add an element at the beginning of the LinkedList

        linkedList.addFirst("Mango");

        System.out.println("After adding at the beginning: " + linkedList);

        // Add an element at the end of the LinkedList

        linkedList.addLast("Grapes");

        System.out.println("After adding at the end: " + linkedList);

        // Get the first and last elements of the LinkedList

        String firstElement = linkedList.getFirst();

        String lastElement = linkedList.getLast();

        System.out.println("First Element: " + firstElement);

        System.out.println("Last Element: " + lastElement);

        // Remove an element from the LinkedList

        linkedList.remove(1); // Remove the element at index 1

        System.out.println("After removing element at index 1: " + linkedList);

        // Check if the LinkedList contains an element

        boolean containsMango = linkedList.contains("Mango");

        System.out.println("Contains Mango? " + containsMango);

        // Get the size of the LinkedList

        int size = linkedList.size();

        System.out.println("Size: " + size);

        // Clear the LinkedList

        linkedList.clear();

        System.out.println("After clearing the LinkedList: " + linkedList);

    }

}

Output:

LinkedList: [Apple, Banana, Orange]

After adding at the beginning: [Mango, Apple, Banana, Orange]

After adding at the end: [Mango, Apple, Banana, Orange, Grapes]

First Element: Mango

Last Element: Grapes

After removing element at index 1: [Mango, Banana, Orange, Grapes]

Contains Mango? true

Size: 4

After clearing the LinkedList: []

PriorityQueue:

import java.util.PriorityQueue;

public class PriorityQueueExample {

    public static void main(String[] args) {

        // Create a PriorityQueue

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

        // Add elements to the PriorityQueue

        priorityQueue.add(5);

        priorityQueue.add(1);

        priorityQueue.add(3);

        priorityQueue.add(2);

        priorityQueue.add(4);

        // Print the PriorityQueue

        System.out.println("PriorityQueue: " + priorityQueue);

        // Retrieve and remove the minimum element from the PriorityQueue

        int minElement = priorityQueue.poll();

        System.out.println("Minimum Element: " + minElement);

        // Print the PriorityQueue after removing the minimum element

        System.out.println("PriorityQueue after poll: " + priorityQueue);

        // Retrieve, but do not remove, the minimum element from the PriorityQueue

        int peekElement = priorityQueue.peek();

        System.out.println("Peeked Element: " + peekElement);

        // Check if the PriorityQueue contains an element

        boolean containsElement = priorityQueue.contains(3);

        System.out.println("Contains 3? " + containsElement);

        // Get the size of the PriorityQueue

        int size = priorityQueue.size();

        System.out.println("Size: " + size);

        // Clear the PriorityQueue

        priorityQueue.clear();

        System.out.println("PriorityQueue after clearing: " + priorityQueue);

    }

}

Output:

PriorityQueue: [1, 2, 3, 5, 4]

Minimum Element: 1

PriorityQueue after poll: [2, 4, 3, 5]

Peeked Element: 2

Contains 3? true

Size: 4

PriorityQueue after clearing: []

Java Queue Interface Implementation

The Java Queue Interface helps developers handle and process data structures more efficiently in Java applications and reorder objects or elements seamlessly. Further, it enables us to manipulate data via implementing classes like LinkedList and PriorityQueue and also works effectively in cases where thread safety is a priority, as it supports safe multithreading without taking up too much space.

Also Read: Getting Started With Java Visualizers To Enhance User Experience

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US