基于值按降序对Map 进行排序

可能重复:
如何在Java中的值上对Map 进行排序?

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

A 34 B 25 c 50 

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

 C 50 A 34 B 25 

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

 static <K,V extends Comparable> SortedSet<Map.Entry> entriesSortedByValues(Map map) { SortedSet<Map.Entry> sortedEntries = new TreeSet<Map.Entry>( new Comparator<Map.Entry>() { @Override public int compare(Map.Entry e1, Map.Entry 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; } 

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

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

 static > List> entriesSortedByValues(Map map) { List> sortedEntries = new ArrayList>(map.entrySet()); Collections.sort(sortedEntries, new Comparator>() { @Override public int compare(Entry e1, Entry e2) { return e2.getValue().compareTo(e1.getValue()); } } ); return sortedEntries; } 

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


例:

 public static void main(String args[]) { Map map = new HashMap(); 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] 

编写自己的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 lMap=new HashMap(); lMap.put("A", 35); lMap.put("B", 25); lMap.put("C", 50); MyComparator comp=new MyComparator(lMap); Map newMap = new TreeMap(comp); newMap.putAll(lMap); 

输出:

 C=50 A=35 B=25