A Queue is a First In First Out (FIFO) data structure. It models a queue in real-life. Yes, the one that you might have seen in front of a movie theater, a shopping mall, a metro, or a bus.

Just like queues in real life, new elements in a Queue data structure are added at the back and removed from the front. A Queue can be visualized as shown in the figure below.

Java Queue Data Structure Visualization

The process of adding an element at the back of the Queue is called Enqueue, and the process of removing an element from the front of the Queue is called Dequeue.

Java provides a Queue interface which is part of Java’s collections framework. The figure below depicts the position of Queue interface in Collections hierarchy -

Java Queue interface in Collection Hierarchy

A Queue in Java is just an interface. We need a concrete implementation of the Queue interface to work with, in our programs.

As shown in the diagram above, the LinkedList class implements the Queue interface and therefore it can be used as a Queue.

Creating a Queue and Performing basic operations like Enqueue and Dequeue

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

public class QueueExample {
    public static void main(String[] args) {
        // Create and initialize a Queue using a LinkedList
        Queue<String> waitingQueue = new LinkedList<>();

        // Adding new elements to the Queue (The Enqueue operation)
        waitingQueue.add("Rajeev");
        waitingQueue.add("Chris");
        waitingQueue.add("John");
        waitingQueue.add("Mark");
        waitingQueue.add("Steven");

        System.out.println("WaitingQueue : " + waitingQueue);

        // Removing an element from the Queue using remove() (The Dequeue operation)
        // The remove() method throws NoSuchElementException if the Queue is empty
        String name = waitingQueue.remove();
        System.out.println("Removed from WaitingQueue : " + name + " | New WaitingQueue : " + waitingQueue);

        // Removing an element from the Queue using poll()
        // The poll() method is similar to remove() except that it returns null if the Queue is empty.
        name = waitingQueue.poll();
        System.out.println("Removed from WaitingQueue : " + name + " | New WaitingQueue : " + waitingQueue);
    }
}
# Output
WaitingQueue : [Rajeev, Chris, John, Mark, Steven]
Removed from WaitingQueue : Rajeev | New WaitingQueue : [Chris, John, Mark, Steven]
Removed from WaitingQueue : Chris | New WaitingQueue : [John, Mark, Steven]

Peek inside the Queue

  • Check if a Queue is empty.
  • Find the size of a Queue.
  • Search for an element in a Queue.
  • Get the element at the front of the Queue without removing it.
import java.util.LinkedList;
import java.util.Queue;

public class QueueSizeSearchFrontExample {
    public static void main(String[] args) {
        Queue<String> waitingQueue = new LinkedList<>();

        waitingQueue.add("Jennifer");
        waitingQueue.add("Angelina");
        waitingQueue.add("Johnny");
        waitingQueue.add("Sachin");

        System.out.println("WaitingQueue : " + waitingQueue);

        // Check is a Queue is empty
        System.out.println("is waitingQueue empty? : " + waitingQueue.isEmpty());

        // Find the size of the Queue
        System.out.println("Size of waitingQueue : " + waitingQueue.size());

        // Check if the Queue contains an element
        String name = "Johnny";
        if(waitingQueue.contains(name)) {
            System.out.println("WaitingQueue contains " + name);
        } else {
            System.out.println("Waiting Queue doesn't contain " + name);
        }

        // Get the element at the front of the Queue without removing it using element()
        // The element() method throws NoSuchElementException if the Queue is empty
        String firstPersonInTheWaitingQueue =  waitingQueue.element();
        System.out.println("First Person in the Waiting Queue (element()) : " + firstPersonInTheWaitingQueue);

        // Get the element at the front of the Queue without removing it using peek()
        // The peek() method is similar to element() except that it returns null if the Queue is empty
        firstPersonInTheWaitingQueue = waitingQueue.peek();
        System.out.println("First Person in the Waiting Queue : " + firstPersonInTheWaitingQueue);

    }
}
# Output
WaitingQueue : [Jennifer, Angelina, Johnny, Sachin]
is waitingQueue empty? : false
Size of waitingQueue : 4
WaitingQueue contains Johnny
First Person in the Waiting Queue (element()) : Jennifer
First Person in the Waiting Queue : Jennifer

Iterating over a Queue in Java

The example in this section shows various ways of iterating over a Queue:

  • Iterate over a Queue using Java 8 forEach() method.
  • Iterate over a Queue using iterator().
  • Iterate over a Queue using iterator() and Java 8 forEachRemaining() method.
  • Iterate over a Queue using simple for-each loop.

The iteration order in a Queue is same as the insertion order.

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

public class IterateOverQueueExample {
    public static void main(String[] args) {
        Queue<String> waitingQueue = new LinkedList<>();

        waitingQueue.add("John");
        waitingQueue.add("Brad");
        waitingQueue.add("Angelina");
        waitingQueue.add("Julia");

        System.out.println("=== Iterating over a Queue using Java 8 forEach() ===");
        waitingQueue.forEach(name -> {
            System.out.println(name);
        });

        System.out.println("\n=== Iterating over a Queue using iterator() ===");
        Iterator<String> waitingQueueIterator = waitingQueue.iterator();
        while (waitingQueueIterator.hasNext()) {
            String name = waitingQueueIterator.next();
            System.out.println(name);
        }

        System.out.println("\n=== Iterating over a Queue using iterator() and Java 8 forEachRemaining() ===");
        waitingQueueIterator = waitingQueue.iterator();
        waitingQueueIterator.forEachRemaining(name -> {
            System.out.println(name);
        });

        System.out.println("\n=== Iterating over a Queue using simple for-each loop ===");
        for(String name: waitingQueue) {
            System.out.println(name);
        }
    }
}
# Output
=== Iterating over a Queue using Java 8 forEach() ===
John
Brad
Angelina
Julia

=== Iterating over a Queue using iterator() ===
John
Brad
Angelina
Julia

=== Iterating over a Queue using iterator() and Java 8 forEachRemaining() ===
John
Brad
Angelina
Julia

=== Iterating over a Queue using simple for-each loop ===
John
Brad
Angelina
Julia

Conclusion

That’s all folks! In this article, you learned what is a Queue data structure, how to create a Queue in Java, how to add new elements to a Queue, how to remove an element from the Queue, and how to search for an element in the Queue.

Thanks for reading. See you in the next post.