You need to use Comparator which will be used to order this priority queue.

Use Comparator.comparing() and pass Method reference of comparing parameter when create the PriorityQueue

PriorityQueue<Pair<Integer,Integer> > pq=
                new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));

Or

You can use lambda expression

PriorityQueue<Pair<Integer,Integer> > pq=
                    new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());
Answer from Eklavya on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-of-pair-in-java-with-examples
Priority Queue of Pair in Java with Examples - GeeksforGeeks
July 23, 2025 - import java.io.*; import java.util.*; import javafx.util.Pair; class GFG { public static void main(String[] args) { // Priority Queue implementing min heap of Pairs // Creating instance of PriorityQueue by passing // Comparator as a constructor parameter PriorityQueue<Pair<Integer, Integer>> pq = new PriorityQueue<>(Comparator.comparing(Pair::getKey)); // Adding objects of Pair<K, V> class by passing // keys and values as parameter in Pair constructor pq.add(new Pair<>(8,80)); pq.add(new Pair<>(4,70)); pq.add(new Pair<>(9,40)); pq.add(new Pair<>(2,85)); // Printing min heap based on the priority while(!pq.isEmpty()){ System.out.print(pq.remove() +" "); } } }
🌐
Baeldung
baeldung.com › home › java › java collections › how to use pair with java priorityqueue
How to Use Pair With Java PriorityQueue | Baeldung
May 4, 2024 - In contrast, Java requires some initial setup with additional classes or interfaces. The PriorityQueue is an excellent data structure to implement more performant and straightforward algorithms. It allows customization with Comparators so that we can provide any sorting rules based on our domain requirements. Combining PriorityQueue and Pairs helps us write more robust and easy-to-understand code. However, it’s often considered a more advanced data structure, and not all developers are fluent with its API.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to Use Pair With Java PriorityQueue - Java Code Geeks
June 12, 2024 - This article explores how to use ... the sorting order. A PriorityQueue is a queue data structure where elements are ordered based on their priority rather than their insertion order. This data structure is part of ...
🌐
GitHub
github.com › stevenhalim › cpbook-code › blob › master › ch2 › nonlineards › priority_queue.java
cpbook-code/ch2/nonlineards/priority_queue.java at master · stevenhalim/cpbook-code
pq.offer(new pair<Integer, String> (70, "martin")); // this is how we use Java PriorityQueue · // priority queue will arrange items in 'heap' based · // on the first key in pair, which is money (integer), largest first · // if first keys tied, use second key, which is name, largest first ·
Author   stevenhalim
🌐
GeeksforGeeks
geeksforgeeks.org › java › priority-queue-in-java
PriorityQueue in Java - GeeksforGeeks
Elements are processed based on priority rather than insertion order. Supports standard queue operations like add(), poll(), and peek(). Automatically grows as elements are added and null insertion is not possible .
Published   3 weeks ago
🌐
Sololearn
sololearn.com › en › Discuss › 3175728 › priority-queue-with-pair-facing-issue
Priority Queue With Pair | Facing Issue | Sololearn: Learn to code for FREE!
Hi Please refer code below: I have priority queue of pair. pair is of score(integer) and id (integer). I need to sort data in pair as below: highest priority for higher score if score is same, highest priority is for lowest id It is not working for me even though I have overloaded < operator for pair.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 8 )
3 weeks ago - Java™ Platform Standard Ed. 8 ... An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
Find elsewhere
🌐
CalliCoder
callicoder.com › java-priority-queue
Java Priority Queue Tutorial with Examples | CalliCoder
February 18, 2022 - Let’s say that we need to create a priority queue of String elements in which the String with the smallest length is processed first. We can create such a priority queue by passing a custom Comparator that compares two Strings by their length.
🌐
Naukri
naukri.com › code360 › library › priority-queue-using-java
Java PriorityQueue: Complete Tutorial - Naukri Code 360
Almost there... just a few more seconds · <img src="https://www.naukri.com/akam/13/pixel_5882bca4?a=dD03N2RmMTAyNjRlNjNiZDI0YjYzOTIwOWQ2Mjk2YTVjYmI5OGEzNzI5JmpzPW9mZg==" style="visibility: hidden; position: absolute; left: -999px; top: -999px;" />
🌐
LeetCode
leetcode.com › problems › maximum-frequency-stack › solutions › 163416 › Java-Priority-Queue-easy-understand
Maximum Frequency Stack - LeetCode
Can you solve this real interview question? Maximum Frequency Stack - Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: * FreqStack() constructs an empty frequency stack.
🌐
freeCodeCamp
freecodecamp.org › news › priority-queue-implementation-in-java
Priority Queues in Java Explained with Examples
September 1, 2024 - Priority queues help consumers consume the higher priority messages first followed by the lower priority messages. Now let's see some actual Java code that will show us how to use priority queues.
Top answer
1 of 4
5

To use JDK's implementation of priority queue for your application, you can maintain a Map<Key, Value> in addition to PriorityQueue<Value>. In your case, Key represents a node and Value is an object that holds the shortest distance to a node. To update the distance to a node, you first look up its corresponding distance object in the map. Then, you remove the distance object from the priority queue. Next, you update the distance object. Finally, you insert the distance object back in the priority queue.

2 of 4
2

Below is the Dijkstra implementation using priority_queue . Here ignore the InputReader class as it is for fast input . We can maintain priority according to "Value" of pair in key value pair . Then choose the Pair with minimum cost i.e value .

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.PriorityQueue;
/** 
 * By: Rajan Parmar
 * At : HackerRank 
 **/
public class Dijkstra { 
     // node ,pair ( neighbor , cost)
    static HashMap < Integer , HashSet <Pair>> node;
    static PrintWriter w;   
    public static void main(String [] s) throws Exception{
        InputReader in;

        boolean online = false;
        String fileName = "input";

        node = new HashMap<Integer, HashSet<Pair>>();


        //ignore online if false it is for online competition
        if (online) {

            //ignore
            in = new InputReader(new FileInputStream(
                    new File(fileName + ".txt")));
            w = new PrintWriter(new FileWriter(fileName + "Output.txt"));
        } else {

            // for fast input output . You can use any input method
            in = new InputReader(System.in);
            w = new PrintWriter(System.out);
        }

        // Actual code starts here
        int t;
        int n, m;
        t = in.nextInt();

        while(t-- > 0){
            n = in.nextInt();
            m = in.nextInt();
            while(m-- > 0){
                int x,y,cost;
                x = in.nextInt();
                y = in.nextInt();
                cost = in.nextInt();

                if(node.get(x)==null){
                    node.put(x, new HashSet());
                    node.get(x).add(new Pair(y,cost));
                }
                else{
                    node.get(x).add(new Pair(y,cost));
                }
                if(node.get(y)==null){
                    node.put(y, new HashSet());
                    node.get(y).add(new Pair(x,cost));
                }
                else{
                    node.get(y).add(new Pair(x,cost));
                }
            }
            int source = in.nextInt();
            Dijkstra(source,n);
            node.clear();
            System.out.println("");
        }
    }

    static void Dijkstra(int start , int n) {

        int dist[] = new int[3001];
        int visited[] = new int[3001];
        Arrays.fill(dist, Integer.MAX_VALUE);
        Arrays.fill(visited, 0);
        dist[start] = 0 ;
        PriorityQueue < Pair > pq = new PriorityQueue();

        //this will be prioritized according to VALUES (i.e cost in class Pair)
        pq.add(new Pair(start , 0));
        while(!pq.isEmpty()){
            Pair pr = pq.remove();
            visited[pr.neighbor] = 1;
            for(Pair p:node.get(pr.neighbor)){
                if(dist[p.neighbor] > dist[pr.neighbor] + p.cost){
                    dist[p.neighbor] = dist[pr.neighbor] + p.cost;

                    //add updates cost to vertex through start vertex
                    if(visited[p.neighbor]==0)
                        pq.add(new Pair(p.neighbor ,dist[p.neighbor] ));
                }

            }
        }
        for(int i=1;i<=n;i++){
            if(i==start) continue;
            if(visited[i]==0)
                dist[i]=-1;
            System.out.print(dist[i]+" ");
        }
    }

    static class Pair implements Comparable {

        int neighbor;
        int cost;

        public Pair(int y, int cost) {
            // TODO Auto-generated constructor stub
            neighbor = y;
            this.cost = cost;
        }

        @Override
        public int compareTo(Object o) {
            // TODO Auto-generated method stub
            Pair pr = (Pair)o;

            if(cost > pr.cost)
                return 1;
            else
                return -1;

        }

    }

    //Ignore this class , it is for fast input.
    static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
}

This will take input in following format .

First line be T (no. of test case).

For each test case next line input will be N and M , where N is no of nodes , M is no of edges.

Next M line contains 3 integers i.e x,y,W. It represents edge between node x and y with weight W.

Next line contain single integer i.e. Source node .

Output :

Print shortest distance to all node from given source node . If node is unreachable print -1.

e.g

Input :

1
6 8
1 2 1
1 5 4
2 5 2
2 3 2
5 6 5
3 6 2
3 4 1
6 4 3
1

Output : (shortest distance of all node from node 1)

1 3 4 3 5
🌐
Sbme-tutorials
sbme-tutorials.github.io › 2020 › data-structure-FALL › notes › week09.html
Week 10: Priority Queues
A priority queue may have multiple entries with equivalent keys, in which case methods min and removeMin may report an arbitrary choice among those entry having minimal key. Values may be any type of object.
🌐
GitHub
apple.github.io › foundationdb › priority-queues-java.html
Priority Queues — FoundationDB 7.4.4 documentation - Apple
The count is derived by reading ... a given priority. By using a snapshot read, we guarantee that pushing is conflict-free. To implement this model, we need an efficient way of finding the first and last key in the queue. (The ordering of keys guarantees that these will always be the proper keys to pop or peek.) FoundationDB’s range reads have limit and reverse options that let us accomplish this. We can find the first and last key-value pairs in the range ...
🌐
Wikipedia
en.wikipedia.org › wiki › Priority_queue
Priority queue - Wikipedia
1 week ago - Priority queue serves highest priority items first. Priority values have to be instances of an ordered data type, and higher priority can be given either to the lesser or to the greater values with respect to the given order relation. For example, in Java standard library, PriorityQueue's the ...
🌐
iO Flood
ioflood.com › blog › java-priority-queue
Java PriorityQueue: Ordering and Organizing Elements
March 11, 2024 - To use a priority queue in Java, you create an instance of PriorityQueue as follows: PriorityQueue<Integer> pq = new PriorityQueue<>();. Once elements are added, they will be ordered based on their natural ordering or by a Comparator provided ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › PriorityQueue.html
PriorityQueue (Java Platform SE 7 )
Java™ Platform Standard Ed. 7 ... An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.