英文:
Java PriorityQueue<Integer> does not sorted by expected
问题
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 sort by the values of the map in a PriorityQueue. The expected result is 0-1-2-4-8-3-5-6-7 or similar, right? However, the current result is 0-1-2-8-4-5-6-7-3. It's obvious that key 7's value is 3, the largest, so it should be at the end. But currently, it appears before 3. I don't understand why this is happening. Thank you.
英文:
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 <br />
0 -> 0,<br />
1 -> 1,<br />
2 -> 1,<br />
3 -> 2,<br />
4 -> 1,<br />
5 -> 2,<br />
6 -> 2,<br />
7 -> 3,<br />
8 -> 1,<br />
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.<br/>
Thanks you.
答案1
得分: 0
PriorityQueue将按自然顺序对项目进行排序。由于它们是整数,它们将按升序排序。
有关如何按所需方式排序的信息,请参阅此处链接。
英文:
PriorityQueue will sort items by the natural order. Since they are integers they will be sorted by ascending order.
See here for how to sort the way you need.
专注分享java语言的经验与见解,让所有开发者获益!
评论