Map按照Value排序(升序,降序)--string

时间:2021-12-18 19:24:10
public class mapValueSort {
public static void main(String[] args) {
HashMap<String,String> map = new HashMap<String,String>();
map.put("19","1");
map.put("12","99");
map.put("11","22");
map.put("99","4");

map = (HashMap<String, String>) sortMapByValueDesc(map) ;//key降序
System.out.println("map按照value倒序排序开始=========");
for(Map.Entry<String, String> maps : map.entrySet()){
System.out.println(maps.getKey() +"=" +maps.getValue());
}

map = (HashMap<String, String>) sortMapByValueAsc(map) ;//key升序
System.out.println("map按照value升序排序开始=========");
for(Map.Entry<String, String> maps : map.entrySet()){
System.out.println(maps.getKey() +"=" +maps.getValue());
}
}
//降序
public static Map<String, String> sortMapByValueDesc(Map<String, String> oriMap) {
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
try {
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 = Integer.parseInt(entry1.getValue());
value2 = Integer.parseInt(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());
}
}
} catch (Exception e) {
}
return sortedMap;
}

//给map排序--值(升序,从小到大) duliyuan
public static Map<String, String> sortMapByValueAsc(Map<String, String> oriMap) {
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
try {
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> entry2,
Entry<String, String> entry1) {
int value2 = 0, value1 = 0;
try {
value2 = Integer.parseInt(entry1.getValue());
value1 = Integer.parseInt(entry2.getValue());
} catch (NumberFormatException e) {
value2 = 0;
value1 = 0;
}
return value1 - value2;
}
});
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());
}
}
} catch (Exception e) {
}
return sortedMap;
}
}


排序结果:

map按照value倒序排序开始=========
12=99
11=22
99=4
19=1
map按照value升序排序开始=========
19=1
99=4
11=22
12=99



Collections.sort只支持String,String的类型