JAVA中hashmap排序的方法是什么
导读:在Java中,HashMap是无序的数据结构,如果需要对HashMap中的键值对进行排序,可以通过以下方法实现: 将HashMap中的键值对转化为List,然后对List进行排序。 HashMap<String, Integer&...
在Java中,HashMap是无序的数据结构,如果需要对HashMap中的键值对进行排序,可以通过以下方法实现:
- 将HashMap中的键值对转化为List,然后对List进行排序。
HashMapString, Integer>
map = new HashMap>
();
// 添加键值对到map
ListMap.EntryString, Integer>
>
list = new ArrayList>
(map.entrySet());
Collections.sort(list, new ComparatorMap.EntryString, Integer>
>
() {
public int compare(Map.EntryString, Integer>
o1, Map.EntryString, Integer>
o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
);
- 使用TreeMap,TreeMap是有序的Map数据结构,可以按照键或值进行排序。
HashMapString, Integer>
map = new HashMap>
();
// 添加键值对到map
TreeMapString, Integer>
sortedMap = new TreeMap>
(new ComparatorString>
() {
public int compare(String o1, String o2) {
return map.get(o1).compareTo(map.get(o2));
}
}
);
sortedMap.putAll(map);
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: JAVA中hashmap排序的方法是什么
本文地址: https://pptw.com/jishu/632662.html
