Open In App

Custom Comparator for a Specific Element type in a PriorityQueue in Java

Last Updated : 17 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

PriorityQueue in Java is a data structure that stores elements according to their specified natural order or comparison. By default, it uses a natural order, but we can also define customized comparisons to sort things out based on specific criteria.

Custom Comparator in PriorityQueue

A Custom Comparator in Java is an interface that defines a method for comparing two objects. It allows us to specify a custom sort for elements that do not have a natural order or when we want to override the default sort. Using a Comparator, we can provide our logic to compare items in a PriorityQueue and determine their priority.

Steps to Implement a Custom Comparator

Follow these steps to create a customized comparison for a specific element type in a PriorityQueue in Java.

  • Create a class that implements the Comparator interface and specifies the element type we want to compare. Let’s call this class GFG.
  • Use the comparison method from the Comparator interface of the GFG class.
    • This method takes two parameters representing the elements to be compared and returns an integer value based on the comparison result. The returned value must follow this rule.
    • Returns a negative integer if the first element should be greater than the first.
    • If the first element should be redundant, a positive integer is returned.
    • Returns zero if the elements have the same priority.
  • Create an instance of PriorityQueue and pass an instance of the GFG class to its constructor. This will cause PriorityQueue to use our custom comparison according to object order.
  • Add elements to the PriorityQueue using the add or offer method. A custom comparator is used to determine the order of the items in the queue.

Program to Implement a Custom Comparator for a Specific Element type in a PriorityQueue in Java

Below is an example of how to implement a custom comparator for a specific element type in a PriorityQueue in Java:

Java
// Java program to Implement a Custom Comparator
import java.util.*;

// Define a class representing a Person
class Person 
{
    private String name;
    private int age;

    // Constructor to initialize name and age
    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    // Getter method for name
    public String getName() 
    { 
      return name; 
    }

    // Getter method for age
    public int getAge() 
    { 
      return age; 
    }
}

// Define a custom comparator to compare Person objects
// based on age
class AgeComparator implements Comparator<Person> 
{
    @Override
    // Override the compare method to define custom
    // comparison logic
    public int compare(Person p1, Person p2)
    {
        // Compare persons based on their ages
        return p1.getAge() - p2.getAge();
    }
}

// Driver Class
public class GFG 
{
      // Main Function
    public static void main(String[] args)
    {
        // Create a PriorityQueue with a custom comparator
        // for Person objects
        PriorityQueue<Person> queue
            = new PriorityQueue<>(new AgeComparator());

        // Create some Person objects
        Person person1 = new Person("Sushmita", 25);
        Person person2 = new Person("Alekya", 30);
        Person person3 = new Person("Geetha", 20);

        // Add Person objects to the PriorityQueue
        queue.offer(person1);
        queue.offer(person2);
        queue.offer(person3);

        // Poll elements from the PriorityQueue and print
        // their details
        while (!queue.isEmpty()) 
        {
            Person person = queue.poll();
            System.out.println("Name: " + person.getName()
                               + ", Age: "
                               + person.getAge());
        }
    }
}

Output
Name: Geetha, Age: 20
Name: Sushmita, Age: 25
Name: Alekya, Age: 30



Explanation of the Program:

  • We created a PriorityQueue of Person objects.
  • Then we have used the AgeComparator as a custom comparator.
  • The Person objects were ordered based on their age, resulting in the output being sorted in ascending order of age.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads