代码如下:
Map<String,Double> map = new HashMap<>();
map.put("设备形态",0d);
map.put("参考单价(元)",2d);
map.put("适用装备分类名称",30d);
map.put("适用装备名称",1d);
map.put("管理部门",6d);
//对map集合,降序排序
List<Map.Entry<String,Double>> list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String,Double>>(){
public int compare(Map.Entry<String,Double> a, Map.Entry<String,Double> b) {
Double res = b.getValue() - a.getValue();
//如果b=a,返回0
if(res==0){
return 0;
}
//如果b>a,返回1
else if(res>0){
return 1;
}
//如果b<a,返回-1
else{
return -1;
}
}
});
// 只有 LinkedHashMap在存储时会按照写入的顺序来
Map<String,Double> resMap = new LinkedHashMap<>();
for(Map.Entry<String,Double> item : list){
resMap.put(item.getKey(), item.getValue());
}
Iterator<Map.Entry<String,Double>> iterator = resMap.entrySet().iterator();
int count = 0;
//由大到小,取前3个
while(iterator.hasNext()) {
if(count == 3){
break;
}
Map.Entry<String,Double> entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
count++;
}
参考:Java map按照值降序排列_打破砂锅问到底007的博客-CSDN博客_map降序排列