I am trying to built a maxheap of characters. First sort by frequency, if frequency is same, then sort alphabetically.
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
Queue<Character> pq = new PriorityQueue<>(new Comparator<Character>(){
@Override
public int compare(Character c1, Character c2){
if(map.get(c1) == map.get(c2)){
return c1 < c2 ? -1 : (c1 == c2 ? 0 : 1);
//return (char)c1 - (char)c2; same output
}
return map.get(c2) - map.get(c1);
}
});
for(char key : map.keySet()){
pq.offer(key);
System.out.println(key + " has freq " + map.get(key));
}
while(!pq.isEmpty()) {
System.out.print(pq.poll() + " ");
}
I put 26 letters into this maxheap, and each letter has same frequency 5000.
But the output order is 'a', 'z', 'y', 'x'...., 'c', 'b'.

when frequency of each char is 5, the order is correct.

I don't understand why the output with frequency 5000 is like this. How can I get a right order?
mapbeing defined?equals()to compare objects, not==.Integers are 5000, they are all different objects, somap.get(c1) == map.get(c2)is false. When they are 5, they are all the same object due to a optimization in Java, and in that casemap.get(c1) == map.get(c2)is true.