Java Queue Interface Tutorial
The Queue Interface
A Queue is a collection for holding elements prior to processing. It is a First In First Out (FIFO) data structure.Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations. The Queue interface follows.
public interface Queue
extends Collection { E element(); boolean offer(E e); E peek(); E poll(); E remove(); }
Each Queue method exists in two forms:
(1) One throws an exception if the operation fails, and
(2) The other returns a special value if the operation fails (either null or false, depending on the operation).
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 add method, which Queue inherits from Collection, inserts an element unless it would violate the queue's capacity restrictions, in which case it throws IllegalStateException. The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates the failure to insert an element by returning false.
Queue implementations generally do not allow the insertion of null elements. The LinkedList implementation, which was retrofitted to implement Queue, is an exception.
Queue implementations generally do not define element-based versions of the equals and hashCode methods but instead inherit the identity based versions from Object.
The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the interface java.util.concurrent.BlockingQueue, which extends Queue
Queue with basic operations
package com.javacodestuffs.core.interfaces.queue; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue
queue = new LinkedList<>(); queue.add("Vasanta"); queue.add("Grisma"); queue.add("Varsa"); queue.add("Sharad"); queue.add("Hemanta"); queue.add("Shishira"); System.out.println("Ecological seasons queue : "); System.out.println(queue); System.out.println(); // Removing an element from the Queue using remove() String name = queue.remove(); System.out.println(name + "Removed from queue and now queue is : " + queue); // Removing an element from the Queue using poll() name = queue.poll(); System.out.println(name + "Removed from queue and now queue is : " + queue); } } output: Ecological seasons queue : [Vasanta, Grisma, Varsa, Sharad, Hemanta, Shishira] VasantaRemoved from queue and now queue is : [Grisma, Varsa, Sharad, Hemanta, Shishira] GrismaRemoved from queue and now queue is : [Varsa, Sharad, Hemanta, Shishira]
Queue with Search,size,empty and get the element operations
package com.javacodestuffs.core.interfaces.queue;
import java.util.LinkedList;
import java.util.Queue;
public class QueueOperations {
public static void main(String[] args) {
Queue < String > queue = new LinkedList < >();
queue.add("Anna");
queue.add("Rashmika");
queue.add("Vedant");
queue.add("Rutuja");
queue.add("Krutika");
System.out.println("Queue is : ");
System.out.println(queue);
// Check if a Queue is empty
System.out.println("\nQueue empty : " + queue.isEmpty());
// size of the Queue
System.out.println("\nSize of Queue : " + queue.size());
// Check if the Queue contains an element
if (queue.contains("Krutika")) {
System.out.println("Queue contains Krutika");
} else {
System.out.println("Queue doesn't contain Krutika");
}
// Get the element at the front of the Queue without removing it using element()
String firstPersonInThequeue = queue.element();
System.out.println("\nFirst Person in the Queue : " + firstPersonInThequeue);
// Get the element at the front of the Queue without removing it using peek()
firstPersonInThequeue = queue.peek();
System.out.println("First Name in Queue is : " + firstPersonInThequeue);
}
}
output:
Queue is :
[Anna, Rashmika, Vedant, Rutuja, Krutika]
Queue empty : false
Size of Queue : 5
Queue contains Krutika
First Person in the Queue : Anna
First Name in Queue is : Anna
Iterating over a Queue usind different ways
Here we will see different ways to iterate queue in java.
package com.javacodestuffs.core.interfaces.queue;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class IterateQueueExample {
public static void main(String[] args) {
Queue < String > queue = new LinkedList < >();
queue.add("Anna");
queue.add("Rashmika");
queue.add("Vedant");
queue.add("Rutuja");
queue.add("Krutika");
System.out.println("::::::::::Iterating Queue using Java 8 forEach() ::::::::::");
queue.forEach(name - >{
System.out.println(name);
});
System.out.println("::::::::::Iterating Queue using iterator() ::::::::::");
Iterator < String > queueIterator = queue.iterator();
while (queueIterator.hasNext()) {
String name = queueIterator.next();
System.out.println(name);
}
System.out.println("::::::::::Iterating Queue using iterator() and Java 8 forEachRemaining() ::::::::::");
queueIterator = queue.iterator();
queueIterator.forEachRemaining(name - >{
System.out.println(name);
});
System.out.println("::::::::::Iterating Queue using for-each loop ::::::::::");
for (String name: queue) {
System.out.println(name);
}
}
}
output:
::::::::::Iterating Queue using Java 8 forEach() ::::::::::
Anna
Rashmika
Vedant
Rutuja
Krutika
::::::::::Iterating Queue using iterator() ::::::::::
Anna
Rashmika
Vedant
Rutuja
Krutika
::::::::::Iterating Queue using iterator() and Java 8 forEachRemaining() ::::::::::
Anna
Rashmika
Vedant
Rutuja
Krutika
::::::::::Iterating Queue using for-each loop ::::::::::
Anna
Rashmika
Vedant
Rutuja
Krutika
Sub-interfaces
Generally, the queue has 3 main subinterfaces.
1). Blocking Queues
2). Transfer Queues
3). Deques
1). Blocking Queues
A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
This interface is implemented by the following classes:
LinkedBlockingQueue — An optionally bounded FIFO blocking queue backed by linked nodes.
ArrayBlockingQueue — A bounded FIFO blocking queue backed by an array.
PriorityBlockingQueue — An unbounded blocking priority queue backed by a heap.
DelayQueue — A time-based scheduling queue backed by a heap.
SynchronousQueue — A simple rendezvous mechanism that uses the BlockingQueue interface.
For more information, please read the article on Blocking Queues.
2). Transfer Queues
A TransferQueue is a queue in which not wait for receipt of the consumer. The data/message will be transferred to consumers as soon as it comes to the blocking queue.
A TransferQueue may be capacity bounded. If so, an attempted transfer operation may initially block waiting for available space, and/or subsequently block waiting for reception by a consumer.
For more information, please read the article on TransferQueue.
3). Deques
It is a double-ended queue. It is a collection that supports element insertion and removal at both ends. Deques can also be used as LIFO (Last-In-First-Out) stacks.
Priority Queues
It is the queue in which we can maintain the default natural order of the inserted element in the queue. We can customize the order using Comparator when we construct the PriorityQueue.
package com.javacodestuffs.core.interfaces.queue; import java.util.* ; public class QueueExample { public static void main(String[] args) { PriorityQueue
queue = new PriorityQueue <>(); queue.add("Vasanta"); queue.add("Grisma"); queue.add("Varsa"); queue.add("Sharad"); queue.add("Hemanta"); queue.add("Shishira"); String element1 = queue.poll(); String element2 = queue.poll(); String element3 = queue.poll(); String element4 = queue.poll(); String element5 = queue.poll(); String element6 = queue.poll(); System.out.println(element1); System.out.println(element2); System.out.println(element3); System.out.println(element4); System.out.println(element5); System.out.println(element6); } } output: Grisma Hemanta Sharad Shishira Varsa Vasanta
For more information, please read the article on Priority Queue in Java .
Post/Questions related to Java Queue Interface Tutorial
How to call the interface method in java?
How to pass the interface as a parameter in java?
How to implement a generic interface in java?
Can you instantiate an interface in java?
Why functional interface introduced in java 8?
Can an interface extend more than one interface in java?
Queue Implementation in Java using Array
In this article, we have seen how to Java Queue Interface Tutorial with examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment