CRT Lecture 47 , 48 , 49 Java Queue
CRT Lecture 47 , 48 , 49 Java Queue
The Queue interface of the Java collections framework provides the functionality of the queue data
structure. It extends the Collection interface.
BlockingQueue
BlockingDeque
Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is because Collection is
the super interface of Queue .
element() - Returns the head of the queue. Throws an exception if the queue is empty.
peek() - Returns the head of the queue. Returns null if the queue is empty.
remove() - Returns and removes
moves the head of the queue. Throws an exception if the queue is
empty.
poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
import java.util.LinkedList;
class Main {
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
Output
Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]
import java.util.PriorityQueue;
class Main {
numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
Output
Queue: [1, 5, 2]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 5]
Java PriorityQueue
The PriorityQueue class provides the functionality of the heap data structure.
It implements the Queue interface
interface.
Unlike normal queues, priority queue elements are retrieved in sorted order.
Suppose, we want to retrieve elements in the ascending order. In this case, the head of the
priority queue will be the smallest element. Once this element is retrieved, the next smallest
element will be the head of the
he queue.
It is important to note that the elements of a priority queue may not be sorted. However, elements
are always retrieved in sorted order.
Creating PriorityQueue
In order to create a priority queue, we must import the java.util.PriorityQueue package. Once we
import the package, here is how we can create a priority queue in Java.
Here, we have created a priority queue without any arguments. In this case, the head of the
priority queue is the smallest element of the queue. And elements are removed in ascending
order from the queue.
However, we can customize the ordering of elements with the help of the Comparator interface. We
will learn about that later in this tutorial.
Methods of PriorityQueue
The PriorityQueue class provides the implementation of all the methods present in
the Queue interface.
For example,
import java.util.PriorityQueue;
class Main {
numbers.add(4);
numbers.add(2);
numbers.offer(1);
} }
Output
PriorityQueue: [2, 4]
Updated PriorityQueue: [1, 4, 2]