-2
PriorityQueue<Pair<String, Integer>> pq = new PriorityQueue<>(
                 (a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
        );

eg. want to sort this {"love":2,"coding":1,"i":2,"leetcode":1} with result as {"i":2,"love":2,"coding":1,"leetcode":1} but the output result is [love=2, coding=1, i=2, leetcode=1]

Can someone help explain why is it?

Progman
  • 16,827
  • 6
  • 33
  • 48
lucy z
  • 1

1 Answers1

0
  1. You need to reverse the order of subtracting the values to get descending order.
  2. You actually need to remove all the elements to see the order.
  3. The Comparator can be written more clearly and succinctly using the Comparator.comparing methods.
PriorityQueue<Pair<String, Integer>> pq = new PriorityQueue<>(
    Comparator.comparing((Pair<String, Integer> p)->p.getValue())
      .reversed().thenComparing(Pair::getKey));
while(!pq.isEmpty()){
    System.out.println(pq.poll());
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thanks for answering this! why when Only numbers are working well to get descending order but does not work when combining with String? like PriorityQueue> pq = new PriorityQueue<>( (a,b) -> b.getValue()- a.getValue() ); – lucy z Jul 12 '21 at 02:36
  • @lucyz The order is not guaranteed when iterating over it (check the documentation). Only when removing elements is the order is guaranteed. – Unmitigated Jul 12 '21 at 14:18