Collections Framework – The Queue Interface

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 Source Code

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

The Queue interface Methods

Each Queue method exists in two forms:
  1. These methods throw an exception if the operation fails.
  • boolean add(E e) - Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
  • E element() - Retrieves, but does not remove, the head of this queue.
  • E remove() - Retrieves and removes the head of this queue.
  1. These methods return a special value if the operation fails (either null or false, depending on the operation).
  • boolean offer(E e) - Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
  • E peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  • E poll() - Retrieves and removes the head of this queue, or returns null if this queue is empty.
Queues typically, but not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to their values. Whatever order is used, the head of the queue is the element that would be removed by a call to remove or poll.
In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.
It is possible for a Queue implementation to restrict the number of elements that it holds; such queues are known as bounded. Some Queue implementations in java.util.concurrent are bounded, but the implementations in java.util are not.

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


Comments