您的位置:首页 > 编程语言 > Java开发

java Map 按值排序

2016-06-21 10:05 459 查看
/**
* Sort map by value
*
* @param map
*            The map to be sorted
* @return The sorted map by value
*/
public static Map<String, Integer> sort(Map<String, Integer> map) {

List<Map.Entry<String, Integer>> infoIds = new ArrayList<>(map.entrySet());

// Sort by DESC
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});

Map<String, Integer> newMap = new LinkedHashMap<>();
for (int i = 0; i < infoIds.size(); i++) {
Entry<String, Integer> id = infoIds.get(i);
newMap.put(id.getKey(), id.getValue());
}

return newMap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Map 排序