/**
* 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;
}
java Map 按值排序
最新推荐文章于 2024-05-30 08:34:38 发布