Java PriorityQueue Comparator

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Overview

If you have worked with java previously then you definitely would have heard about this amazing data structure called a Priority queue and also a special something called a comparator. You can put something in your priority queue and get back the results in sorted order or more precisely, according to each element's relative priority. It lets you do amazing things, whether you want to sort your marks from best to worst or to arrange your friends from most annoying to least annoying, you can do that with the help of priority queues. But do you know how a priority queue decides an element's relative priority and decide which elements need to be on top of the queue and which don't? Well, it uses an interface called Comparator and a comparator lets you define how and on what basis you what your priority queue to sort the elements. In this article, you'll learn how a priority queue uses the Java priority queue Comparator to achieve its goal.

Introduction

Before we move ahead, let's look at one simple example to understand how things work on a surface level.

Let us imagine a scenario where you have 3 tasks to complete.

  1. you want to pick up a new game that just launched from the game shop.
  2. you have to submit an assignment for your college that is due today.
  3. lastly, you also have to do the laundry that you have been avoiding for the past few days.

Now let us say you have a bad memory and you want to use a data structure in which you can store all your tasks and keep checking that data structure at regular intervals to see which task you have to perform next. That way you don't have to worry about forgetting to complete a particular task and can also manage your time. for this, You can go for a normal list structure such as an ArrayList which will linearly store all your tasks, or you can use a Queue which will store and present your tasks exactly in the order that you entered them in. First in First out (FIFO) remember?

But let us think for a second if this approach will work or not. do you think all your tasks have the same priority? Do you think doing your laundry or buying a new video game is as important as completing an assignment that is due today? No right. So you want to use a data structure that will store and present your data according to their appropriate priority so that you can complete the tasks with maximum priorities first. This is where the Java priority queue comes in. It stores the data with the maximum priority at the top so you can extract your data according to its relevant importance. It uses a function that is used for comparison to decide the ordering of the elements and this function is called the Java priority queue Comparator function.

If you want to learn more about the data structure mentioned above or revise some of the old concepts, you can head over to the Scaler Topics website by using the following links and start learning.

In this article, we are not going to go deep inside what a Java priority queue is and how it works internally in java. you can learn more about it here. In this article, we are mainly going to focus on how we can use the java priority queue and comparator interface to order our data.

Let's look at a straightforward java program to see how Java priority queues work.

A normal queue will return our data in the order that we entered it, but Let's see what happens when we run this code.

Output

As you can see, elements in a priority queue are not stored in the order they were entered in. By default, elements in a java priority queue are stored according to their natural ordering (ascending order for integers) or they are ordered according to the comparator that is provided while creating the priority queue. The priority of each element and how it will be evaluated can be defined in the compare method of the class implementing the Comparator interface associated with the particular priority queue.

Java priority queue comparator is an interface that we can implement and write some code to decide the relative priority of 2 objects of the same class. We can also pass this comparator to our Priority queue to decide the order of our elements or custom class objects in the priority queue. It uses the compare method to decide the priority. compare method takes in 2 objects of the same type, and its syntax looks something like this-

But enough with the jargon, let's look at some examples and understand how things work.

Java Program to Create a Custom Comparator in Java Using PriorityQueue

Let us say we created our custom class named CustomDemoClass and we want to create a Priority Queue that will store instances of our custom class i.e. our custom class objects. We will need to implement the comparator interface and provide the compare method to tell java how and on what grounds we want our objects to be sorted. Let's see how that will look like

First, let's see the output, and then we will try to understand the code line by line.

Output:

Now let's try to understand the code. We start by declaring a priority queue.

Here we are declaring our priority queue that will store objects of our custom class and we are passing an object of our custom comparator to it by the name of OurCustomComparator.

class OurCustomComparator implements Comparator

Here we are defining our comparator by implementing the Comparator interface and providing the compare method in the class which sorts our objects in descending order of their age attribute. Remember, our custom class has 2 attributes, name and age.

System.out.println(pq.poll().getName()); Here we are just extracting the objects from the priority queue based on their priority as defined in the comparator and printing the name attribute for each object while the queue is not empty. We are using the getName() method to get the name attribute for each object. This method is defined in our custom class.

We can also sort the objects based on the name attribute just by changing the custom comparator class, more precisely, by changing the compare method inside the class slightly.

Output:

Java Program to Create a Comparator Directly in Java Using PriorityQueue

In the previous example, we saw that we can create our custom comparator and pass it to the priority queue so that we can sort our custom class objects inside the priority queue. But here's when things become interesting, Java provides you with some ways to implement your comparator directly to your priority queue. Let's see how

Output:

As you can see, the above java code also sorts our objects based on the descending order of their age attribute However, without needing to define the comparator class separately. we have provided the code for the java priority queue comparator directly to the priority queue.

We can do a similar thing for sorting our objects based on the name attribute

Output:

There you go, That's how you use and implement the Java priority queue Comparator. If you want to learn more about interfaces, inheritance, and other related java concepts, you can use some of the following links.

Conclusion

  1. Priority queues store data in a sorted manner according to the comparator provided to the priority queue.
  2. By default, primitives Elements are stored in their natural order.
  3. We can create our comparator by implementing the comparator interface and providing the compare method which takes in 2 objects of the same class as arguments
  4. priority queue uses this compare method to decide which object should be given higher priority and which should be given lower priority
  5. you can write your comparator separately and pass it to the priority queue constructor
  6. You can also provide the implementation of the comparator directly to the priority queue constructor.

Thank you for reading. Keep learning.