java -- 对Map按键、按值排序
1.按键排序(sort by key)
直接上代码 ↓
public Map<String, String> sortMapByKey(Map<String, String> oriMap) {
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String key1, String key2) {
int intKey1 = 0, intKey2 = 0;
try {
intKey1 = getInt(key1);
intKey2 = getInt(key2);
} catch (Exception e) {
intKey1 = 0;
intKey2 = 0;
}
return intKey1 - intKey2;
}});
sortedMap.putAll(oriMap);
return sortedMap;
} private int getInt(String str) {
int i = 0;
try {
Pattern p = Pattern.compile("^\\d+");
Matcher m = p.matcher(str);
if (m.find()) {
i = Integer.valueOf(m.group());
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return i;
}
2.按值排序(sort by value)
按值排序就相对麻烦些了,没有直接可用的数据结构能处理类似需求,需要我们自己转换一下。
public Map<String, String> sortMapByValue(Map<String, String> oriMap) {
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
if (oriMap != null && !oriMap.isEmpty()) {
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
Collections.sort(entryList,
new Comparator<Map.Entry<String, String>>() {
public int compare(Entry<String, String> entry1,
Entry<String, String> entry2) {
int value1 = 0, value2 = 0;
try {
value1 = getInt(entry1.getValue());
value2 = getInt(entry2.getValue());
} catch (NumberFormatException e) {
value1 = 0;
value2 = 0;
}
return value2 - value1;
}
});
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
}
return sortedMap;
}
3. 后记
如果map存储的是<String,对象>类型的数据 可以让对象实现java.lang.Comparable<>接口,并按照你自己的排序规则重写compareTo方法!