Java Queue Interface

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.

Queue Interface declaration

Methods of Java 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.

PriorityQueue class

The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO manner. It inherits AbstractQueue class.

PriorityQueue class declaration

Let's see the declaration for java.util.PriorityQueue class.

Java PriorityQueue Example

Test it Now
Output:head:Amit
       head:Amit
       iterating the queue elements:
       Amit
       Jai
       Karan
       Vijay
       Rahul
       after removing two elements:
       Karan
       Rahul
       Vijay

Java PriorityQueue Example: Book

Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in PriorityQueue, you need to implement 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




Contact US

Email:[email protected]

Queue & PriorityQueue
10/30