Java Queue is an interface available in java.util package and extends java.util.Collection interface. Just like Java List, Java Queue is a collection of ordered elements (Or objects) but it performs insert and remove operations differently. We can use Queue to store elements before processing those elements.
In this section, we will discuss some of the important points about Java Queue:
Java Queue interface extends Collection interface. Collection interface extends Iterable interface. Some of the frequently used Queue implementation classes are LinkedList, PriorityQueue, ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue etc… AbstractQueue provides a skeletal implementation of the Queue interface to reduce the effort in implementing Queue.
In this section we will discuss some of the useful and frequently used Java Queue methods:
As Java Queue extends Java Collection, it also supports all Collection interface operations. Let’s explore some simple operations in the following example:
package com.journaldev.queue;
import java.util.*;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("one");
queue.add("two");
queue.add("three");
queue.add("four");
System.out.println(queue);
queue.remove("three");
System.out.println(queue);
System.out.println("Queue Size: " + queue.size());
System.out.println("Queue Contains element 'two' or not? : " + queue.contains("two"));
// To empty the queue
queue.clear();
}
}
Output:-
[one, two, three, four]
[one, two, four]
Queue Size: 3
Queue Contains element 'two' or not? : true
Here we can explore how to convert a Java array to Queue using “Collections.addAll()” method with one simple example.
import java.util.*;
public class ArrayToQueue {
public static void main(String[] args) {
String nums[] = {"one","two","three","four","five"};
Queue<String> queue = new LinkedList<>();
Collections.addAll(queue, nums);
System.out.println(queue);
}
}
Output:- When we run above program, We will get the following output:
[one, two, three, four, five]
Here we will explore how to convert a Java Queue to a Java Array using “toArray()” with one simple example.
import java.util.*;
public class QueueToArray {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("one");
queue.add("two");
queue.add("three");
queue.add("four");
queue.add("five");
String strArray[] = queue.toArray(new String[queue.size()]);
System.out.println(Arrays.toString(strArray));
}
}
Output:- When we run above program, We will get the following output:
[one, two, three, four, five]
Java Queue supports all operations supported by Collection interface and some more operations. It supports almost all operations in two forms.
The following table explains all Queue common operations briefly.
Operation | Throws exception | Special value |
---|---|---|
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
We will pickup each operation and discuss them in-detail with some useful examples in the coming sections.
In this section, we will discuss about Java Queue Insert operation in-detail with some useful examples. If this operation performs successfully, it returns “true” value. As we know, Queue supports insert operation in two forms:
NOTE:- Here special value may be either “false” or “null”
The add() operation is used to insert new element into the queue. If it performs insert operation successfully, it returns “true” value. Otherwise it throws java.lang.IllegalStateException. Let us develop one simple example to demonstrate this functionality.
import java.util.concurrent.*;
public class QueueAddOperation {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
System.out.println(queue.add("one"));
System.out.println(queue.add("two"));
System.out.println(queue);
System.out.println(queue.add("three"));
System.out.println(queue);
}
}
Output:- When we run above program, We will get the following output:
true
true
[one, two]
Exception in thread "main" java.lang.IllegalStateException: Queue full
As our queue is limited to two elements, when we try to add third element using BlockingQueue.add(), it throws an exception as shown above.
The offer() operation is used to insert new element into the queue. If it performs insert operation successfully, it returns “true” value. Otherwise it returns “false” value. Let us develop one simple example to demonstrate this functionality.
import java.util.concurrent.*;
public class QueueOfferOperation {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
System.out.println(queue.offer("one"));
System.out.println(queue.offer("two"));
System.out.println(queue);
System.out.println(queue.offer("three"));
System.out.println(queue);
}
}
Output:- When we run above program, We will get the following output:
true
true
[one, two]
false
[one, two]
As our queue is limited to two elements, when we try to add third element using BlockingQueue.offer() operation, it returns “false” value as shown above.
In this section, we will discuss about Java Queue Delete operation in-detail with some useful examples. The Delete operations returns the head element of the queue, if it performs successfully. As we know, Queue supports delete operation in two forms:
NOTE:- Here special value may be either “false” or “null”
The remove() operation is used to delete an element from the head of the queue. If it performs delete operation successfully, it returns the head element of the queue. Otherwise it throws java.util.NoSuchElementException. Let us develop one simple example to demonstrate this functionality.
import java.util.*;
public class QueueRemoveOperation
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<>();
queue.offer("one");
queue.offer("two");
System.out.println(queue);
System.out.println(queue.remove());
System.out.println(queue.remove());
System.out.println(queue.remove());
}
}
Output:- When we run above program, We will get the following output:
[one, two]
one
two
Exception in thread "main" java.util.NoSuchElementException
As our queue has only two elements, when we try to call remove() method for third time, it throws an exception as shown above. NOTE:- Queue.remove(element) is used to delete a specified element from the queue. If it performs delete operation successfully, it returns “true” value. Otherwise it returns “false” value.
The poll() operation is used to delete an element from the head of the queue. If it performs delete operation successfully, it returns the head element of the queue. Otherwise it returns “null” value. Let us develop one simple example to demonstrate this functionality.
import java.util.*;
public class QueuePollOperation
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<>();
queue.offer("one");
queue.offer("two");
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
}
}
Output:- When we run above program, We will get the following output:
[one, two]
one
two
null
As our queue has only two elements, when we try to call poll() method for third time, it returns null value as shown above.
In this section, we will discuss about Java Queue Examine operations in-detail with some useful examples. If this operation performs successfully, it returns the head element of the queue without removing it. As we know, Queue supports examine operation in two forms:
NOTE:- Here special value may be either “false” or “null”
The element() operation is used to retrieve an element from the head of the queue, without removing it. If it performs examine operation successfully, it returns the head element of the queue. Otherwise it throws java.util.NoSuchElementException. Let us develop one simple example to demonstrate this functionality.
import java.util.*;
public class QueueElementOperation {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("one");
System.out.println(queue.element());
System.out.println(queue);
queue.clear();
System.out.println(queue.element());
}
}
Output:- When we run above program, We will get the following output:
one
[one]
Exception in thread "main" java.util.NoSuchElementException
If we try to call element() method on empty Queue, it throws an exception as shown above.
The peek() operation is used to retrieve an element from the head of the queue, without removing it. If it performs examine operation successfully, it returns the head element of the queue. Otherwise it returns null value. Let us develop one simple example to demonstrate this functionality.
import java.util.*;
public class QueuePeekOperation {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("one");
System.out.println(queue.peek());
System.out.println(queue);
queue.clear();
System.out.println(queue.peek());
}
}
Output:- When we run above program, We will get the following output:
one
[one]
null
If we try to call peek() method on empty Queue, it returns null value, but does NOT throw an exception as shown above.
In Java, we can find many Queue implementations. W can broadly categorize them into the following two types
Bounded Queues are queues which are bounded by capacity that means we need to provide the max size of the queue at the time of creation. For example ArrayBlockingQueue (see previous example). Unbounded Queues are queues which are NOT bounded by capacity that means we should not provide the size of the queue. For example LinkedList (see previous example). All Queues which are available in java.util package are Unbounded Queues and Queues which are available in java.util.concurrent package are Bounded Queues. In other ways, W can broadly categorize them into the following two types:
All Queues which implement BlockingQueue interface are BlockingQueues and rest are Non-Blocking Queues. BlockingQueues blocks until it finishes it’s job or time out, but Non-BlockingQueues do not. Some Queues are Deques and some queues are PriorityQueues.
In addition to Queue’s two forms of operations, BlockingQueue’s supports two more forms as shown below.
Operation | Throws exception | Special value | Blocks | Times out |
---|---|---|---|---|
Insert | add(e) | offer(e) | put(e) | offer(e, time, unit) |
Remove | remove() | poll() | take() | poll(time, unit) |
Examine | element() | peek() | N/A | N/A |
Some operations are blocked until it finishes it’s job and other are blocked until time out. That’s all of a quick roundup on Queue in Java. I hope these Java Queue examples will help you in getting started with Queue collection programming. Please drop me a comment if you like my tutorials or have any suggestions or issues or type errors. Thank you.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Very informative. Appreciate your work.
- Sonam
Good tut0rials, thanks so much!
- kevin hu