In this guide, we will learn about Queue interface, it's methods and it's implementation classes.
The Queue Interface Overview
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 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:
These methods throw an exception if the operation fails.
- boolean add(E e) - This method 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() - This method retrieves, but does not remove, the head of this queue.
- E remove() - This method retrieves and removes the head of this queue.
- boolean offer(E e) - This method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
- E peek() - This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
- E poll() - This method retrieves and removes the head of this queue, or returns null if this queue is empty.
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 with It's LinkedList Implementation Class Example
Creating a Queue using LinkedList implementation class 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
General purpose implementation class:
All Known Implementing Classes:
AbstractQueue, ArrayBlockingQueue, ArrayDeque, ConcurrentLinkedDeque, ConcurrentLinkedQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, SynchronousQueue
References
https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/util/Queue.htmlFree Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment