Here's a Comparator that sorts Map.Entry objects using Comparable keys and values:
public class ValueThenKeyComparator<K extends Comparable<? super K>, V extends Comparable<? super V>> implements Comparator<Map.Entry<K, V>> { public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) { int cmp1 = a.getValue().compareTo(b.getValue()); if (cmp1 != 0) { return cmp1; } else { return a.getKey().compareTo(b.getKey()); } } }
You put all the map entries in a list, and then sorted this:
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(h.entrySet()); Collections.sort(list, new ValueThenKeyComparator<String, Integer>());
source share