/**
* 对map集合的value进行降序排列方法
* @param map 需要排序的map集合
* @param <K> 键
* @param <V> 值
*/
public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry:list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
//对上面的方法进行调用测试
@Test
void testMap(){
//需要排序的map集合
Map map = new HashMap<>();
map.put("key", 12211);
map.put("key1", 221222);
map.put("key2", 333);
map.put("key3", 442214);
map.put("key4", 5521215);
map.put("key5", 6211266);
map.put("key6", 7712217);
map.put("key7", 2121888);
map.put("key8", 4343443);
map.put("key9", 788787);
map.put("key10", 455454);
map.put("key11", 43434);
map.put("key12", 3444343);
System.out.println("排序之前: "+map);
//根据value值进行降序排列
Map resultMap = MapUtil.sortDescend(map);
System.out.println("排序之后:"+resultMap);
}
//结果
排序之前: {key1=221222, key2=333, key5=6211266, key6=7712217, key3=442214, key4=5521215, key9=788787, key7=2121888, key8=4343443, key11=43434, key10=455454, key12=3444343, key=12211}
排序之后:{key6=7712217, key5=6211266, key4=5521215, key8=4343443, key12=3444343, key7=2121888, key9=788787, key10=455454, key3=442214, key1=221222, key11=43434, key=12211, key2=333}