如何对hashmap按value值排序

http://bbs.csdn.net/topics/90321713

这个帖子中没有我想要的答案,treemap是根据key排序的,想以value排序,那么可以key,value互换一下,不过这样的话key(换了之后现在的key是原来的value)就不能重复了

 

http://www.programcreek.com/2013/03/java-sort-map-by-value/

 1 import java.util.Comparator;
 2 import java.util.HashMap;
 3 import java.util.Map;
 4 import java.util.TreeMap;
 5  
 6 public class Solution {
 7     public static void main(String[] args) {
 8         HashMap<String, Integer> map = new HashMap<String, Integer>();
 9         map.put("a", 10);
10         map.put("b", 30);
11         map.put("c", 50);
12         map.put("d", 40);
13         map.put("e", 20);
14         System.out.println(map);
15  
16         Map sortedMap = sortByValue(map);
17         System.out.println(sortedMap);
18     }
19  
20     public static Map sortByValue(Map unsortedMap) {
21         Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
22         sortedMap.putAll(unsortedMap);
23         return sortedMap;
24     }
25  
26 }
27  
28 class ValueComparator implements Comparator {
29  
30     Map map;
31  
32     public ValueComparator(Map map) {
33         this.map = map;
34     }
35  
36     public int compare(Object keyA, Object keyB) {
37         Comparable valueA = (Comparable) map.get(keyA);
38         Comparable valueB = (Comparable) map.get(keyB);
39         return valueB.compareTo(valueA);  //这个是降序   升序是valueA.compareTo(valueB) 
40 }
41 }

但是这个  如果value是重复的话  只会显示一个

eg 

a  1

b  1

c  1

 

结果只会显示 a  1

感觉这个还是相当于是treemap的把key 和value互换之后的效果

 

 

 1 public static Map sortByValue(Map unsortMap) {     
 2     List list = new LinkedList(unsortMap.entrySet());
 3  
 4     Collections.sort(list, new Comparator() {
 5         public int compare(Object o1, Object o2) {
 6             return ((Comparable) ((Map.Entry) (o1)).getValue())
 7                         .compareTo(((Map.Entry) (o2)).getValue());
 8         }
 9     });
10  
11     Map sortedMap = new LinkedHashMap();
12     for (Iterator it = list.iterator(); it.hasNext();) {
13         Map.Entry entry = (Map.Entry) it.next();
14         sortedMap.put(entry.getKey(), entry.getValue());
15     }
16     return sortedMap;
17 }

这个是我想要的

 

posted on 2014-08-18 22:48  crane_practice  阅读(1793)  评论(0编辑  收藏  举报

导航