Java PriorityQueue не опросы в порядке убыванияJAVA

Программисты JAVA общаются здесь
Anonymous
Java PriorityQueue не опросы в порядке убывания

Сообщение Anonymous »

может кто -нибудь объяснить мне, почему это выводит [AccountB (200), AccountC (200), Accounta (200)] вместо [Accounts (200), AccountB (200), AccountC (200)]?
public static void main(String[] args) {
Map map = new HashMap();
map.put("accountB", 200);
map.put("accountA", 200);
map.put("accountC", 200);
System.out.println(getTopSpenders(map, 5));
}

static public List getTopSpenders(Map map, int n) {
PriorityQueue maxHeap = new PriorityQueue(new Comparator() {
@Override
public int compare(Map.Entry a, Map.Entry b) {
if (a.getValue() != b.getValue()) {
return Integer.compare(b.getValue(), a.getValue());
}
return a.getKey().compareTo(b.getKey());
}
});

for (var entry : map.entrySet()) {
maxHeap.offer(entry);
}

List topSpenders = new ArrayList();
for (int i = 0; i < n; i++) {
if (maxHeap.isEmpty()) {
break;
}

var spender = maxHeap.poll();
String sb = spender.getKey() + "(" + spender.getValue() + ")";
topSpenders.add(sb);
}

return topSpenders;
}


Подробнее здесь: https://stackoverflow.com/questions/794 ... ding-order

Вернуться в «JAVA»