Java Queue Interface Example Tutorial

A Queue follows the FIFO mechanism: the first inserted element will be removed first. For getting a queue behavior, you can create a LinkedList object and refer it through a Queue reference. When you call the methods from Queue reference, the object behaves like a Queue.
Learn collections at https://www.javaguides.net/p/java-collections-tutorial.html.
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.

The Queue interface methods

The Queue interface source code in Java Library shows all its methods:
public interface Queue<E> extends Collection<E> {
    E element();
    boolean offer(E e);
    E peek();
    E poll();
    E remove();
}

The Queue interface Class Diagram

The below diagram shows a list of methods Queue interface provides.

The Queue interface Hierarchy Diagram

Queue interface extends Collection interface and provides provide additional insertion, removal, and inspection operations.

The Queue interface Examples

Creating a Queue and Performing basic operations like Enqueue and Dequeue

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

/**
 * Demonstrate Queue interface methods with LinkedList implementation.
 * @author javaguides.net
 *
 */
public class QueueExample {
    public static void main(String[] args) {
        // Create and initialize a Queue using a LinkedList
        Queue<String> elementQueue = new LinkedList<>();

        // Adding new elements to the Queue (The Enqueue operation)
        elementQueue.add("element1");
        elementQueue.add("element2");
        elementQueue.add("element3");
        elementQueue.add("element4");

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

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

        // 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 = elementQueue.poll();
        System.out.println("Removed from WaitingQueue : " + name + " | New WaitingQueue : " + elementQueue);
    }
}
Output:
WaitingQueue : [element1, element2, element3, element4]
Removed from WaitingQueue : element1 | New WaitingQueue : [element2, element3, element4]
Removed from WaitingQueue : element2 | New WaitingQueue : [element3, element4]

Queue interface methods - isEmpty(), size(), element(), peek()

Let's demonstrate Queue interface methods - isEmpty(), size(), element(),peek() with examples.
  • 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;

/**
 * Demonstrate Queue interface methods with LinkedList implementation.
 * @author javaguides.net
 *
 */

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

        elementQueue.add("element1");
        elementQueue.add("element2");
        elementQueue.add("element3");
        elementQueue.add("element4");

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

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

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

        // Check if the Queue contains an element
        String name = "Johnny";
        if(elementQueue.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 firstElementInTheWaitingQueue =  elementQueue.element();
        System.out.println("Waiting Queue (element()) : " + firstElementInTheWaitingQueue);

        // 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
        firstElementInTheWaitingQueue = elementQueue.peek();
        System.out.println("Waiting Queue : " + firstElementInTheWaitingQueue);

    }
}
Output:
WaitingQueue : [element1, element2, element3, element4]
is waitingQueue empty? : false
Size of waitingQueue : 4
Waiting Queue doesn't contain Johnny
Waiting Queue (element()) : element1
Waiting Queue : element1

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 a simple for-each loop.
  • The iteration order in a Queue is the same as the insertion order.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Iterate over Queue with different approaches.
 * @author javaguides.net
 *
 */

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

        elementsQueue.add("element1");
        elementsQueue.add("element2");
        elementsQueue.add("element3");
        elementsQueue.add("element4");

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

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

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

        System.out.println("\n=== Iterating over a Queue using simple for-each loop ===");
        for(String name: elementsQueue) {
            System.out.println(name);
        }
    }
}
Output:
=== Iterating over a Queue using Java 8 forEach() ===
element1
element2
element3
element4

=== Iterating over a Queue using iterator() ===
element1
element2
element3
element4

=== Iterating over a Queue using iterator() and Java 8 forEachRemaining() ===
element1
element2
element3
element4

=== Iterating over a Queue using simple for-each loop ===
element1
element2
element3
element4

Queue Interface Implementations

LinkedList class is a general implementation of Queue Interface. 
Learn more about LinkedList APIs with examples on Guide to LinkedList Class
Learn collections at https://www.javaguides.net/p/java-collections-tutorial.html.

Comments