您需要列出键,根据相应的值对它们进行排序,然后循环访问排序的键。
Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
System.out.println(key + ": " + map.get(key));
}
至于使用什么,这里有一些方便的,通用的比较器创建例程,我经常发现很有用。第一个根据值的自然顺序按值排序,第二个允许您指定任意比较器来对值进行排序:someComparator
public static <K, V extends Comparable<? super V>>
Comparator<K> mapValueComparator(final Map<K, V> map) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return map.get(key1).compareTo(map.get(key2));
}
};
}
public static <K, V>
Comparator<K> mapValueComparator(final Map<K, V> map,
final Comparator<V> comparator) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return comparator.compare(map.get(key1), map.get(key2));
}
};
}