【发布时间】:2015-11-26 19:30:17
【问题描述】:
我试图先按值(整数)然后按键(字符串)对 HashMap 进行排序。以下方法似乎无法正确排序哈希图。任何想法如何使其正常工作?
private static Map<String, Integer> sortHash(Map<String, Integer> map) {
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
// Sort list by integer values then by string keys
Collections.sort(list, (a, b) -> {
int cmp1 = a.getValue().compareTo(b.getValue());
if (cmp1 != 0)
return cmp1;
else
return a.getKey().compareTo(b.getKey());
});
Map<String, Integer> result = new HashMap<>();
for (Map.Entry<String, Integer> entry : list)
result.put(entry.getKey(), entry.getValue());
return result;
}
【问题讨论】: