根据值</key,value>以降序对Map <key,value>进行排序

时间:2012-07-25 10:37:54

标签: java map hashmap

  

可能重复:
  How to sort a Map<Key, Value> on the values in Java?

我使用map接口从文件中读取,然后将值存储为键值对。文件格式如下

 A 34
 B 25
 c 50

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

C 50
A 34
B 25

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

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;
    }

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

2 个答案:

答案 0 :(得分:48)

由于您可以拥有重复值,因此您根本不应使用Set。更改为List并进行排序。您的entriesSortedByValues看起来像这样:

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]

答案 1 :(得分:13)

编写您自己的comparator并将其传递给TreeMap

class MyComparator implements Comparator {

Map map;

public MyComparator(Map map) {
    this.map = map;
}

public int compare(Object o1, Object o2) {

    return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));

}
}

在测试类中

Map<String, Integer> lMap=new HashMap<String, Integer>();
    lMap.put("A", 35);
    lMap.put("B", 25);
    lMap.put("C", 50);

    MyComparator comp=new MyComparator(lMap);

    Map<String,Integer> newMap = new TreeMap(comp);
    newMap.putAll(lMap);

<强>输出:

C=50
A=35
B=25