Java Queue Interface
The Queue interface is part of the Java Collections Framework and is used to store elements that are waiting to be processed.
A queue commonly follows the FIFO principle:
First In, First OutThis means the element that enters the queue first is generally processed first.
A real-world example is a line of customers waiting at a counter.
Customer 1 → Customer 2 → Customer 3
↓
Processed firstIn Java, the Queue interface provides methods for adding, removing, and examining elements.
Why Do We Need Queue?
Many applications need to process tasks in the order they arrive.
For example, imagine a print system:
Document A
Document B
Document CIf Document A was submitted first, it should normally be processed first.
A queue can represent this behavior:
Queue<String> printQueue = new LinkedList<>();
printQueue.offer("Document A");
printQueue.offer("Document B");
printQueue.offer("Document C");The processing order is:
Document A → Document B → Document CCreating a Queue
Queue is an interface, so we normally create an object using one of its implementations.
For example:
Queue<String> queue = new LinkedList<>();Another common implementation is:
Queue<Integer> queue = new PriorityQueue<>();The behavior of the queue depends on the implementation being used.
Common Queue Implementations
Some commonly used implementations are:
Queue
|
+-- LinkedList
|
+-- PriorityQueue
|
+-- ArrayDequeEach implementation has different characteristics.
LinkedList
Can be used as a general-purpose Queue or Deque.
Queue<String> queue = new LinkedList<>();PriorityQueue
Processes elements according to priority rather than simple insertion order.
Queue<Integer> queue = new PriorityQueue<>();ArrayDeque
Provides an efficient double-ended queue and can also be used for stack-like operations.
Deque<String> deque = new ArrayDeque<>();Adding Elements to a Queue
There are two commonly used methods:
queue.add("Java");and:
queue.offer("Java");Both attempt to add an element.
The important difference is how they behave when the queue cannot accept the element.
- add() throws IllegalStateException when a capacity limit prevents insertion.
- offer() returns false when a capacity limit prevents insertion. Invalid elements can still cause exceptions, such as NullPointerException when null is not allowed.
For many queue implementations, offer() is convenient when you want a success/failure result instead of an exception.
Removing Elements
Two commonly used methods are:
queue.remove();and:
queue.poll();The difference appears when the queue is empty:
- remove() throws an exception.
- poll() returns null.
For example:
Queue<String> queue = new LinkedList<>();
System.out.println(queue.poll());Output
nullReading the Head Element
To examine the next element without removing it, use:
queue.peek();Another method is:
queue.element();The difference when the queue is empty is:
- peek() returns null.
- element() throws an exception.
Queue Method Summary
| Operation | Exception-based method | Special-value method |
|---|---|---|
| Insert | add() | offer() |
| Remove | remove() | poll() |
| Examine | element() | peek() |
This is an important pattern to remember when working with the Queue interface.
Example of FIFO Behavior
import java.util.LinkedList;
import java.util.Queue;
public class HelloWorld {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer("Customer 1");
queue.offer("Customer 2");
queue.offer("Customer 3");
System.out.println("Queue: " + queue);
System.out.println("Processing: " + queue.poll());
System.out.println("Processing: " + queue.poll());
System.out.println("Processing: " + queue.poll());
}
}Output
Queue: [Customer 1, Customer 2, Customer 3]
Processing: Customer 1
Processing: Customer 2
Processing: Customer 3Checking the Queue
Checking Size
System.out.println(queue.size());Checking Whether It Is Empty
if (queue.isEmpty()) {
System.out.println("Queue is empty");
}Checking Whether an Element Exists
if (queue.contains("Customer 2")) {
System.out.println("Customer found");
}Iterating Through a Queue
You can use an enhanced for loop:
for (String item : queue) {
System.out.println(item);
}However, iteration order and processing/removal order should be understood based on the particular Queue implementation.
For example, a PriorityQueue does not guarantee that iterating over it will produce elements in priority order. Its poll() operation is the appropriate way to repeatedly retrieve elements according to priority.
Queue Example: Task Processing
import java.util.LinkedList;
import java.util.Queue;
public class HelloWorld {
public static void main(String[] args) {
Queue<String> tasks = new LinkedList<>();
tasks.offer("Generate Report");
tasks.offer("Send Email");
tasks.offer("Backup Data");
while (!tasks.isEmpty()) {
String task = tasks.poll();
System.out.println("Processing: " + task);
}
}
}Output
Processing: Generate Report
Processing: Send Email
Processing: Backup DataQueue vs Stack
| Feature | Queue | Stack |
|---|---|---|
| Common principle | FIFO | LIFO |
| First processed | First added for a FIFO implementation | Last added |
| Add | offer() | push() |
| Remove | poll() | pop() |
| Examine | peek() | peek() |
| Example | Waiting line | Stack of plates |
Queue vs List
A List focuses on storing an ordered sequence with index-based access.
A Queue focuses on processing elements according to a queue policy.
For example:
List<String> list = new ArrayList<>();supports:
list.get(0);while:
Queue<String> queue = new LinkedList<>();is normally used with:
queue.offer("A");
queue.poll();When Should You Use Queue?
Use a Queue when elements need to be processed according to a queue policy.
Common examples include:
- Task processing
- Print queues
- Request processing
- Message processing
- Customer waiting systems
- Breadth-first search
Important Points
- Queue is an interface.
- FIFO is a common queue-processing principle.
- offer() adds an element.
- poll() removes the head.
- peek() examines the head.
- PriorityQueue uses priority ordering instead of simple FIFO behavior.
- Different Queue implementations can provide different behavior.
- Queue can contain duplicate elements unless the implementation imposes different restrictions.
Key Takeaway
The Java Queue interface is used when elements need to be processed in a defined queue order. For ordinary FIFO processing, implementations such as LinkedList or ArrayDeque can be used, while PriorityQueue is useful when elements need to be processed according to priority.
See you in next page....🙂