JAVA对Map按Value排序
public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map){
class MapClass{ //自定义类保存键值对
private String key;
private int value;
public MapClass(String key, int value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
}
class MapSortMethod implements Comparator<MapClass>{ //为自定义类实现排序方法
@Override
public int compare(MapClass o1, MapClass o2) {
int result = Integer.compare(o1.getValue(), o2.getValue()); //按值大小升序排列
//int result = ((), ()); //按值大小降序排列
if(result != 0)
return result;
return o1.getKey().compareTo(o2.getKey()); //值相同时按键字典顺序排列
}
}
ArrayList<MapClass> mapclass = new ArrayList<MapClass>(); //以ArrayList保存自定义类
for(String k: map.keySet())
mapclass.add(new MapClass(k, map.get(k)));
Collections.sort(mapclass, new MapSortMethod()); //使用()方法,第二个参数为自定义排序方法,需要实现Comparator接口
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for(MapClass m: mapclass)
sortedMap.put(m.getKey(), m.getValue());
return sortedMap; //用LinkedHashMap返回排好序的Map
}