Java Queue Interface is used to store elements in a specific order, usually following the First-In-First-Out (FIFO) principle. It is commonly used in real-life scenarios like task scheduling and order processing. You will also learn different examples to understand how Queue works in Java.
In this chapter, you will learn about the Java Queue interface, its features, working, and examples.
The Queue interface belongs to the java.util package and is a part of the Java Collections Framework. It is used to store elements in an ordered way where elements are added at the end and removed from the beginning.
Queue follows the FIFO (First-In-First-Out) principle, which makes it useful for applications like task scheduling, print queues, and order management.
Queue is an interface, so it cannot be created directly. It is implemented by classes like LinkedList and PriorityQueue.
The Queue interface is declared as an interface that extends the Collection interface.
Here is the syntax:
The following table shows the commonly used methods of the Queue interface:
| Method | Description |
|---|---|
| boolean add(object) | It is used to insert the specified element into this queue and return true upon success. |
| boolean offer(object) | It is used to insert the specified element into this queue. |
| Object remove() | It is used to retrieves and removes the head of this queue. |
| Object poll() | It is used to retrieves and removes the head of this queue, or returns null if this queue is empty. |
| Object element() | It is used to retrieves, but does not remove, the head of this queue. |
| Object peek() | It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. |
The following are some important features of a queue.
PriorityQueue is a class in the Java Collection Framework that is used to process elements based on priority.
In a normal queue, elements follow the FIFO (First-In-First-Out) order. However, in PriorityQueue, elements are processed according to their priority instead of insertion order.
The PriorityQueue class extends AbstractQueue and implements Serializable.
Here is the syntax:
Here are some examples of the Java PriorityQueue class to understand its usage.
In this example, we are creating a PriorityQueue, adding elements, and performing different operations like peek(), remove(), and poll().
Output:
head:Amit head:Amit iterating the queue elements: Amit Jai Karan Vijay Rahul after removing two elements: Karan Rahul Vijay
In this example, we are storing user-defined Book objects in a PriorityQueue using the Comparable interface.
Output:
Traversing the queue elements: 101 Data Communications & Networking Forouzan Mc Graw Hill 4 233 Operating System Galvin Wiley 6 121 Let us C Yashwant Kanetkar BPB 8 After removing one book record: 121 Let us C Yashwant Kanetkar BPB 8 233 Operating System Galvin Wiley 6
We request you to subscribe our newsletter for upcoming updates.