I have a simple class that fills in a simple hashmap I want to order values by hashcode how to do that?
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Ch11Ex18 {
public static void main(String[] args) {
Random rand = new Random(47);
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
for(int i = 0; i < 10000; i++) {
// Produce a number between 0 and 20:
int r = rand.nextInt(20);
Integer freq = m.get(r);
m.put(r, freq == null ? 1 : freq + 1);
}
System.out.println(m);
}
}
You don’t:
HashMapis inherently unordered.You could use
TreeMapwith a custom comparator, but then you should be aware that if you use unequal objects with the same hash code, only one of them will end up in the map… and even so this would order by the keys rather than the values.You could create an
ArrayList<Integer>containing a copy of the values, and sort that – but then you won’t have the keys.You could create an
ArrayList<Map.Entry<Integer, Integer>>containing a copy of the entries, and sort that… but really, what’s the point?Fundamentally, this is an odd thing to do – hash codes should not be used like this, basically. They’re not unique, shouldn’t be viewed as a source of randomness, etc. Whatever the bigger picture is here, there’s pretty much bound to be a better approach.