Map<Integer, Integer> map = new HashMap<>();
for (int n : arr) map.put(n, map.getOrDefault(n, 0) + 1);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> map.get(a) - map.get(b));
for (int n : arr) pq.add(n);
while (!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
Assume the input arr is [4,3,1,1,3,3,2,2] and after we put them all inside the pq and poll them one by one. the correct order should be 4 1 1 2 2 3 3 3 in the order of frequency.
But the output order is 4 1 2 2 1 3 3 3 which didn't output the correct order.