0

I want to sort the values in in ascending order by values of HashMap in Priority Queue.

HashMap<Integer, Integer> map = new HashMap<>();
    map.put(1, 1);
    map.put(2, 5);
    map.put(3, 2);
    map.put(4,4);

  PriorityQueue<Map.Entry<Integer,
            Integer>> minHeap
            = new PriorityQueue<>(
            (a, b)
                    -> a.getValue().equals(b.getValue())
                    ? Integer.compare(a.getKey(),
                    b.getKey())
                    : Integer.compare(a.getValue(),
                    b.getValue()));

    for(Map.Entry<Integer,Integer> entry:map.entrySet()){
      minHeap.add(entry);
    }

    System.out.println(minHeap);

Output [1=1, 4=4, 3=2, 2=5]

Can anyone suggest why the order is not coming in ascending order by values

coder25
  • 2,363
  • 12
  • 57
  • 104
  • Does this answer your question? [What is wrong with my comparable interface logic?](https://stackoverflow.com/questions/63809189/what-is-wrong-with-my-comparable-interface-logic) Please note how the second answer (actually, written by me) explains that PriorityQueue respects ordering only on queue semantics (add, poll, ...) and not on its iterator (which is internally used when calling toString as you do) – GPI Apr 07 '21 at 15:23
  • @GPI I have done it on simliar lines, not sure why my answer is not correct, if values are same then I check keys – coder25 Apr 07 '21 at 15:36
  • The issue is not the comparator, it is the printing of the result. The queue is well ordered, but to actually observe that order, you must use it as a `Queue`, and not as an `Iterable`. E.g. change `System.out.println(minHeap)` with `while(!minHeap.isEmpty()) {System.out.println(minHeap.poll());}` – GPI Apr 07 '21 at 15:49
  • @GPI you must use it as a Queue, and not as an Iterable , can you explain – coder25 Apr 07 '21 at 16:02
  • I did in the linked answer (see my first comment). https://stackoverflow.com/a/63809957/2131074 Using as a `Queue` means using only methods from the `Queue` interface, and not using it as an `Iterable` means not calling `.iterator()` (which `priorityQueue.toString()` does, internally) – GPI Apr 07 '21 at 16:15
  • https://stackoverflow.com/a/5695085/2244676 – Oleks Apr 07 '21 at 17:38

0 Answers0