排序地图<Key,Value>根据值降序排列 [英] Sorting the Map<Key,Value> in descending order based on the value

查看:22
本文介绍了排序地图<Key,Value>根据值降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何对地图进行排序<键、值>关于 Java 中的值?

我正在使用映射接口从文件中读取数据,然后将其中的值存储为键值对.文件格式如下

I am using map interface to read from a file and then store the values in that as a key value pair. The file format is as follows

 A 34
 B 25
 c 50

我将从该文件中读取数据并将其存储为键值对,然后将其显示给用户.我的要求是以这种格式显示结果

I will read the datas from this file and store that as a key value pair and then I will display this to the user. My requirement is to display the results in this format

C 50
A 34
B 25

因此我需要按值的降序对地图进行排序.这样我就可以将这些显示为我的结果..我已经阅读了这个并找到了下面的代码

Thus I need to sort the map in descending order of the value. So that I will be able to display these as my result .. I have read about this and find the below code

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

我希望这是按升序对值进行排序,我只是想知道这种方法是否正确或其他一些有效的方法对我有帮助吗?

I hope this is gonna sort the values in ascending order, I just want to know whether this approach is correct or some other effective approach will be helpful for me ?

推荐答案

既然你可以有重复的值,你根本不应该使用 Set.改为 List 并对其进行排序.您的 entriesSortedByValues 看起来像这样:

Since you can have duplicate values you shouldn't be using a Set at all. Change to a List and sort it instead. Your entriesSortedByValues would look something like this:

static <K,V extends Comparable<? super V>> 
            List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {

    List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());

    Collections.sort(sortedEntries, 
            new Comparator<Entry<K,V>>() {
                @Override
                public int compare(Entry<K,V> e1, Entry<K,V> e2) {
                    return e2.getValue().compareTo(e1.getValue());
                }
            }
    );

    return sortedEntries;
}

注意:在您的示例输出中,值是递减的.如果您希望它们升序,请改用 e1.getValue().compareTo(e2.getValue()).

public static void main(String args[]) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 34);
    map.put("B", 25);
    map.put("C", 50);
    map.put("D", 50); // "duplicate" value

    System.out.println(entriesSortedByValues(map));
}

输出:

[D=50, C=50, A=34, B=25]

这篇关于排序地图&lt;Key,Value&gt;根据值降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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