public class SortUtils {
// Map的value值升序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortAsc(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(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;
}
}
Map根据Value进行排序
最新推荐文章于 2024-06-06 11:24:10 发布
该博客介绍了如何使用Java对Map的值进行升序排序。通过创建一个Entry的List,然后利用Collections.sort()方法结合自定义比较器完成排序。最后,将排序后的Entry集合转换为新的LinkedHashMap返回。

3327

被折叠的 条评论
为什么被折叠?



