0
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);     
        long n = sc.nextLong();
        HashMap<String, PriorityQueue<Long>> hmap = new HashMap<String, PriorityQueue<Long>>();

        for (long i = 0; i < n; ++i) {

            String s = sc.next();
            long m = sc.nextLong();

            if(hmap.containsKey(s))
                hmap.get(s).add(m);
            else {
                PriorityQueue<Long> maxHeap = new PriorityQueue<Long>(Collections.reverseOrder());
                maxHeap.add(m);
                hmap.put(s, maxHeap);
            }
        }

        for (String str : hmap.keySet()) {
            System.out.println(str);
            System.out.println(hmap.get(str));
        }
}

Hi - I am learning how to use data structures in Java. Here, I am trying to use the PriorityQueue as a Max-Heap. But when I am printing the PriorityQueue associated with each String in the Hashmap - the numbers are not in the descending order as I would have expected. Could someone help me understand why ?

nerd1996
  • 1
  • 1
  • Explain what is your problem. What does not work? What is expected output? – Michał Krzywański Jun 03 '20 at 13:52
  • @michalk Hi. I added an explanation of my expected output – nerd1996 Jun 03 '20 at 13:58
  • Where are you printing your PriorityQueue? Can you modify your code so that anyone can just copy'n'paste it and run it and see the results that you're getting? – Scratte Jun 03 '20 at 14:00
  • @Scratte Hi. I just added the code I am using for printing the PriorityQueue – nerd1996 Jun 03 '20 at 14:04
  • Ok. So, all this is going on in a `main()` method? (This is why you're suppose to make it so that we can just pick it up and run it. It avoids guessing) You should also include the output that your see and the output you expected to see, like michalk asked for. Like exactly what output you get :) But.. alas, you're in luck, michalk found answers for you :) – Scratte Jun 03 '20 at 14:06
  • Note: I'm pretty sure you get your "strange" order in your print because internally, it's stored as a binary tree, but you'd have to check the implementation to be sure. – Scratte Jun 03 '20 at 14:12
  • @michalk Thanks a lot ! That answers my question – nerd1996 Jun 03 '20 at 14:14
  • @Scratte Yups. Youre right. Using poll() is the way to go – nerd1996 Jun 03 '20 at 14:15
  • Read the docs of `PriorityQueue` and you will get the answer there. In short iterator of priority queue does not respect the priority order defined by comparator. The internal implementation holds elements in an array of elements which is not sorted due to priority. – Michał Krzywański Jun 03 '20 at 14:17

0 Answers0