I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys
You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.
Map map = getMyMap();
List keys = new ArrayList(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
System.out.println(key + ": " + map.get(key));
}
As for what to use for someComparator, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:
public static >
Comparator mapValueComparator(final Map map) {
return new Comparator() {
public int compare(K key1, K key2) {
return map.get(key1).compareTo(map.get(key2));
}
};
}
public static
Comparator mapValueComparator(final Map map,
final Comparator comparator) {
return new Comparator() {
public int compare(K key1, K key2) {
return comparator.compare(map.get(key1), map.get(key2));
}
};
}