I have a problem about PriorityQueue.
public static void main(String[] args) {
sortByBits(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8});
System.out.println(1);
}
public static int[] sortByBits(int[] arr) {
Map<Integer, Integer> m = new HashMap<>();
PriorityQueue<Integer> p = new PriorityQueue<>((a, b) -> {
if (m.get(a) == m.get(b)) {
return a - b;
} else {
return m.get(a) - m.get(b);
}
});
for (int i = 0; i < arr.length; i++) {
m.put(arr[i], Integer.bitCount(arr[i]));
p.offer(arr[i]);
}
int[] result = new int[p.size()];
int size = p.size();
for (int i = 0; i < size; i++) {
result[i] = p.poll();
}
return result;
}
Map m is
0 -> 0,
1 -> 1,
2 -> 1,
3 -> 2,
4 -> 1,
5 -> 2,
6 -> 2,
7 -> 3,
8 -> 1,
I wanna sorted by map's value in PriorityQueue, expected result is 0-1-2-4-8-3-5-6-7 or others right ,
but now is 0-1-2-8-4-5-6-7-3, it's obvious that key 7's value is 3,the biggest, should at the end...but now the end is 3, I don't know why.
Thanks you.