排序映射<键,值>按价值观 [英] Sort a Map&lt;Key, Value&gt; by values

查看:24
本文介绍了排序映射<键,值>按价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java比较陌生,经常发现需要对一个Map的值进行排序.

I am relatively new to Java, and often find that I need to sort a Map<Key, Value> on the values.

由于值不是唯一的,我发现自己将 keySet 转换为 array,然后通过 array sort 对该数组进行排序自定义比较器,根据与键关联的值进行排序.

Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key.

有没有更简单的方法?

推荐答案

这是一个通用的友好版本:

Here's a generic-friendly version:

public class MapUtil {
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
        list.sort(Entry.comparingByValue());

        Map<K, V> result = new LinkedHashMap<>();
        for (Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }
}

这篇关于排序映射<键,值>按价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆