Open In App

How to Configure Java Priority Queue to Handle Duplicate Elements?

In Java, PriorityQueue is the data structure that stores the elements based on their priorities and provides operations to efficiently retrieve and manipulate these elements based on their priorities. PriorityQueue handles the duplicate elements using a comparator. Comparator is a pre-defined interface, and it is part of the java.util package. It is used to define a custom ordering for objects of a class that do not have a natural ordering.

In this article, we will learn how to configure Java Priority Queue to handle duplicate elements.



Syntax:

Comparator<T> comparator = (o1, o2) -> {
    //Compare o1 and o2 and return an integer
    // If o1 ordered before o2, it will return negative integer
    // If o1 and o2 are considered equal, it returns zero.
    // If o1 ordered after o2, it will return positive integer
};

Here,

Step-by-Step Implementation

Program to Configure Priority Queue to Handle Duplicate Elements in Java

Below is the Program to Configure Priority Queue to Handle Duplicate Elements:






// Java program to configure Priority Queue to handle duplicate elements
import java.util.Comparator;
import java.util.PriorityQueue;
  
public class GfgComparator 
{
    public static void main(String args[]) 
    {
        // define a custom comparator that considers elements equal if they have the same value
        Comparator<Integer> customComparator = Comparator.comparingInt(i -> i);
          
        // create PriorityQueue with the custom comparator
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(customComparator);
          
        // add elements to the PriorityQueue 
        priorityQueue.add(5);
        priorityQueue.add(2);
        priorityQueue.add(7);
        priorityQueue.add(2); // duplicate elements
        priorityQueue.add(5); // duplicate elements
        
       // print the PriorityQueue
      System.out.println(priorityQueue);
    }
}

Output
[2, 2, 7, 5, 5]

Explanation of the Program:

Note: The order of elements in the output may vary due to the nature of priority queues.


Article Tags :