Search code examples
javaalgorithmhashmappriority-queue

Can't understand Priority Queue process


        String S = "aaaaaaaacabbbb";

        if (S == null || S.length() == 0) {
            return;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (char c : S.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (b.getValue() - a.getValue()));
        pq.addAll(map.entrySet());
        System.out.println(pq);

So, I understood that for this particular snippet, highest priority is given to the key with maximum value, when I print the queue, I get

[a=9, b=4, c=1]

but when I use this comparator

PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (a.getValue() - b.getValue()));

I didnt understand why it gives

[c=1, a=9, b=4]

I thought b would be second, and a would be last

2nd problem

Also, when I added an entry

  Map.Entry<Character, Integer> entry =
 new java.util.AbstractMap.SimpleEntry<Character, Integer>('a', 5);
            pq.offer(entry);

I get this output

[c=1, a=5, b=4, a=9]

Don't understand how the a goes last now


Solution

  • Quoting javadoc of PriorityQueue:

    The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).