Queue Interface In Java
The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in an order where elements are added at the rear and removed from the front.
Key Features:
- FIFO Order – Elements are processed in the order they were inserted (First-In-First-Out).
- No Random Access – Unlike List, elements cannot be accessed directly by index.
- Multiple Variants – Includes PriorityQueue, Deque, ArrayDeque, and LinkedList implementations.
- Two Sets of Methods – Throws-exception versions (add, remove, element) and safe versions (offer, poll, peek).
Declaration of Java Queue Interface
The Queue interface is declared as:
public interface Queue extends Collection
We cannot instantiate a Queue directly as it is an interface. Here, we can use a class like LinkedList or PriorityQueue that implements this interface.
Queue<Obj> queue = new LinkedList<Obj>();
Now let us go through a simple example first, then we will deep dive into the article.
Example: Basic Queue using LinkedList
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String args[])
{
// Create a Queue of Integers using LinkedList
Queue<Integer> q = new LinkedList<>();
System.out.println("Queue elements: " + q);
}
}
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String args[])
{
// Create a Queue of Integers using LinkedList
Queue<Integer> q = new LinkedList<>();
System.out.println("Queue elements: " + q);
}
}
Output
Queue elements: []
Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java. Note that neither of these implementations is thread-safe. PriorityBlockingQueue is one alternative implementation if the thread-safe implementation is needed.
Creating Queue Objects
Queue is an interface, so objects cannot be created of the type queue. We always need a class which extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the Queue. This type-safe queue can be defined as:
// Obj is the type of the object to be stored in Queue
Queue<Obj> queue = new PriorityQueue<Obj> ();
// Obj is the type of the object to be stored in Queue
Queue<Obj> queue = new PriorityQueue<Obj> ();
Common Methods
The Queue interface provides several methods for adding, removing, and inspecting elements in the queue. Here are some of the most commonly used methods:
- add(element): Adds an element to the rear of the queue. If the queue is full, it throws an exception.
- offer(element): Adds an element to the rear of the queue. If the queue is full, it returns false.
- remove(): Removes and returns the element at the front of the queue. If the queue is empty, it throws an exception.
- poll(): Removes and returns the element at the front of the queue. If the queue is empty, it returns null.
- element(): Returns the element at the front of the queue without removing it. If the queue is empty, it throws an exception.
- peek(): Returns the element at the front of the queue without removing it. If the queue is empty, it returns null.
Example 1: This example demonstratesbasic queue operations.
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// add elements to the queue
queue.add("apple");
queue.add("banana");
queue.add("cherry");
System.out.println("Queue: " + queue);
// remove the element at the front of the queue
String front = queue.remove();
System.out.println("Removed element: " + front);
// print the updated queue
System.out.println("Queue after removal: " + queue);
// add another element to the queue
queue.add("date");
// peek at the element at the front of the queue
String peeked = queue.peek();
System.out.println("Peeked element: " + peeked);
// print the updated queue
System.out.println("Queue after peek: " + queue);
}
}
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// add elements to the queue
queue.add("apple");
queue.add("banana");
queue.add("cherry");
System.out.println("Queue: " + queue);
// remove the element at the front of the queue
String front = queue.remove();
System.out.println("Removed element: " + front);
// print the updated queue
System.out.println("Queue after removal: " + queue);
// add another element to the queue
queue.add("date");
// peek at the element at the front of the queue
String peeked = queue.peek();
System.out.println("Peeked element: " + peeked);
// print the updated queue
System.out.println("Queue after peek: " + queue);
}
}
Output
Queue: [apple, banana, cherry] Removed element: apple Queue after removal: [banana, cherry] Peeked element: banana Queue after peek: [banana, cherry, date]
Example 2:
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String[] args){
Queue<Integer> q = new LinkedList<>();
// Adds elements {0, 1, 2, 3, 4} to the queue
for (int i = 0; i < 5; i++)
q.add(i);
// Display contents of the queue
System.out.println("Elements of queue: " + q);
// To remove the head of queue
int removedele = q.remove();
System.out.println("Removed element:"+ removedele);
System.out.println(q);
// To view the head of queue
int head = q.peek();
System.out.println("Head of queue:"+ head);
// Rest all methods of collection interface like size and contains can be used with this implementation.
int size = q.size();
System.out.println("Size of queue:" + size);
}
}
import java.util.LinkedList;
import java.util.Queue;
public class Geeks {
public static void main(String[] args){
Queue<Integer> q = new LinkedList<>();
// Adds elements {0, 1, 2, 3, 4} to the queue
for (int i = 0; i < 5; i++)
q.add(i);
// Display contents of the queue
System.out.println("Elements of queue: " + q);
// To remove the head of queue
int removedele = q.remove();
System.out.println("Removed element:"+ removedele);
System.out.println(q);
// To view the head of queue
int head = q.peek();
System.out.println("Head of queue:"+ head);
// Rest all methods of collection interface like size and contains can be used with this implementation.
int size = q.size();
System.out.println("Size of queue:" + size);
}
}
Output
Elements of queue: [0, 1, 2, 3, 4] Removed element:0 [1, 2, 3, 4] Head of queue:1 Size of queue:4
Classes that implement the Queue Interface
1. PriorityQueue
PriorityQueue class lets us process elements based on their priority instead of the usual FIFO order of a normal queue. It’s useful when elements must be handled in priority order. Here’s how we can create a queue using this class.
Example:
import java.util.*;
class Geeks {
public static void main(String args[]){
// Creating empty priority queue
Queue<Integer> pq = new PriorityQueue<Integer>();
// Adding items to the pQueue using add()
pq.add(10);
pq.add(20);
pq.add(15);
// Printing the top element of the PriorityQueue
System.out.println(pq.peek());
// Printing the top element and removing it the PriorityQueue container
System.out.println(pq.poll());
// Printing the top element again
System.out.println(pq.peek());
}
}
import java.util.*;
class Geeks {
public static void main(String args[]){
// Creating empty priority queue
Queue<Integer> pq = new PriorityQueue<Integer>();
// Adding items to the pQueue using add()
pq.add(10);
pq.add(20);
pq.add(15);
// Printing the top element of the PriorityQueue
System.out.println(pq.peek());
// Printing the top element and removing it the PriorityQueue container
System.out.println(pq.poll());
// Printing the top element again
System.out.println(pq.peek());
}
}
Output
10 10 15
2. LinkedList
LinkedList is a linear data structure where elements are stored as separate objects, each containing data and a link to the next element. The elements are connected using pointers, not stored in continuous memory. Here’s how we can create a queue using this class.
Example:
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating empty LinkedList
Queue<Integer> ll = new LinkedList<Integer>();
// Adding items to the ll using add()
ll.add(10);
ll.add(20);
ll.add(15);
// Printing the top element of the LinkedList
System.out.println(ll.peek());
// Printing the top element and removing it from the LinkedList container
System.out.println(ll.poll());
// Printing the top element again
System.out.println(ll.peek());
}
}
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating empty LinkedList
Queue<Integer> ll = new LinkedList<Integer>();
// Adding items to the ll using add()
ll.add(10);
ll.add(20);
ll.add(15);
// Printing the top element of the LinkedList
System.out.println(ll.peek());
// Printing the top element and removing it from the LinkedList container
System.out.println(ll.poll());
// Printing the top element again
System.out.println(ll.peek());
}
}
Output
10 10 20
3. PriorityBlockingQueue
PriorityBlockingQueue is a thread-safe, unbounded blocking queue that orders elements like PriorityQueue and supports blocking retrieval. Since it’s unbounded, adding elements can still fail if memory runs out. Here’s how to create a queue using this class.
Example:
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating empty priority blocking queue
Queue<Integer> pbq = new PriorityBlockingQueue<Integer>();
// Adding items to the pbq using add()
pbq.add(10);
pbq.add(20);
pbq.add(15);
// Printing the top element of the PriorityBlockingQueue
System.out.println(pbq.peek());
// Printing the top element and removing it from the PriorityBlockingQueue
System.out.println(pbq.poll());
// Printing the top element again
System.out.println(pbq.peek());
}
}
import java.util.concurrent.PriorityBlockingQueue;
import java.util.*;
class Geeks {
public static void main(String args[])
{
// Creating empty priority blocking queue
Queue<Integer> pbq = new PriorityBlockingQueue<Integer>();
// Adding items to the pbq using add()
pbq.add(10);
pbq.add(20);
pbq.add(15);
// Printing the top element of the PriorityBlockingQueue
System.out.println(pbq.peek());
// Printing the top element and removing it from the PriorityBlockingQueue
System.out.println(pbq.poll());
// Printing the top element again
System.out.println(pbq.peek());
}
}
Output
10 10 15
Different Operations on Queue Interface using PriorityQueue class
1. Adding Elements
To add an element in a queue, we can use the add() method. The insertion order is not retained in the PriorityQueue. The elements are stored based on the priority order which is ascending by default.
Example:
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println(pq);
}
}
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println(pq);
}
}
Output
[For, Geeks, Geeks]
2. Removing Elements
To remove an element from a queue, we can use the remove() method. If there are multiple objects, then the first occurrence of the object is removed. The poll() method is also used to remove the head and return it.
Example:
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println("Initial Queue: " + pq);
pq.remove("Geeks");
System.out.println("After Remove: " + pq);
System.out.println("Poll Method: " + pq.poll());
System.out.println("Final Queue: " + pq);
}
}
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
System.out.println("Initial Queue: " + pq);
pq.remove("Geeks");
System.out.println("After Remove: " + pq);
System.out.println("Poll Method: " + pq.poll());
System.out.println("Final Queue: " + pq);
}
}
Output
Initial Queue: [For, Geeks, Geeks] After Remove: [For, Geeks] Poll Method: For Final Queue: [Geeks]
3. Iterating the Queue
There are multiple ways to iterate through the Queue. The most famous way is converting the queue to the array and traversing using the for loop. The queue has also an inbuilt iterator which can be used to iterate through the queue.
Example:
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
Iterator iterator = pq.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
import java.util.*;
public class Geeks {
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("Geeks");
pq.add("For");
pq.add("Geeks");
Iterator iterator = pq.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
Output
For Geeks Geeks
Methods of Queue Interface
Here’s the full method list for the Queue<E> interface in Java, along with all methods it inherits from Collection<E> and Iterable<E>.
Method | Description |
---|---|
boolean add(E e) | Inserts element; throws exception if full. |
boolean offer(E e) | Inserts element; returns false if full. |
E remove() | Removes head; throws exception if empty. |
E poll() | Removes head; returns null if empty. |
E element() | Retrieves head; throws exception if empty. |
E peek() | Retrieves head; returns null if empty. |
boolean addAll(Collection<? extends E> c) | Adds all elements from another collection. |
void clear() | Removes all elements. |
boolean contains(Object o) | Checks if element exists. |
boolean containsAll(Collection<?> c) | Checks if all elements exist. |
boolean equals(Object o) | Compares with another collection. |
int hashCode() | Returns hash code. |
boolean isEmpty() | Checks if collection is empty. |
Iterator<E> iterator() | Returns iterator for elements. |
boolean remove(Object o) | Removes a specific element. |
boolean removeAll(Collection<?> c) | Removes all matching elements. |
boolean retainAll(Collection<?> c) | Keeps only specified elements. |
int size() | Returns number of elements. |
Object[] toArray() | Returns elements as an array. |
<T> T[] toArray(T[] a) | Returns elements as a typed array. |
default void forEach(Consumer<? super E> action) | Performs action for each element. |
default void forEach(Consumer<? super E> action) | Performs action for each element. |
default Spliterator<E> spliterator() | Returns a spliterator. |
default Stream<E> stream() | Returns a sequential stream. |
default Stream<E> parallelStream() | Returns a parallel stream. |