Map 排序
HashMap、Hashtable、LinkedHashMap排序
注:TreeMap也可以使用此方法进行排序,但是更推荐下面的方法。
Map<String, String> map = new HashMap<String, String>();
map.put("b", "b");
map.put("a", "c");
map.put("c", "a");
// 通过ArrayList构造函数把map.entrySet()转换成list
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
// 通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
return mapping1.getKey().compareTo(mapping2.getKey());
}
});
for (Map.Entry<String, String> mapping : list) {
System.out.println(mapping.getKey() + " :" + mapping.getValue());
}
TreeMap排序
TreeMap默认按key进行升序排序,如果想改变默认的顺序,可以使用比较器:
Map<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 降序排序
return o1.compareTo(o2);
}
});
map.put("b", "b");
map.put("a", "c");
map.put("c", "a");
for (String key : map.keySet()) {
System.out.println(key + " :" + map.get(key));
}
按value排序(通用)
Map<String, String> map = new TreeMap<String, String>();
map.put("b", "b");
map.put("a", "c");
map.put("c", "a");
// 通过ArrayList构造函数把map.entrySet()转换成list
List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
// 通过比较器实现比较排序
Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
return mapping1.getValue().compareTo(mapping2.getValue());
}
});
for (String key : map.keySet()) {
System.out.println(key + " :" + map.get(key));
}