public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("11","aa");
map.put("1","aa");
map.put("2","bb");
map.put("22","bb");
map.put("3","cc");
Map<String, String> newMap = sortMapByKey(map, true);
System.out.println(JSON.toJSON(newMap));
}
public static Map<String, String> sortMapByKey(Map<String, String> oriMap, final boolean isRise) {
if (oriMap == null || oriMap.isEmpty())
return null;
Map<String, String> sortMap = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (isRise) {// 升序排序
return o1.compareTo(o2);
} else {// 降序排序
return o2.compareTo(o1);
}
}
});
sortMap.putAll(oriMap);
return sortMap;
}
作者:梓晓
网友评论