Map根据value进行排序

1  TreeMap按照value进行排序

[java]  view plain  copy
  1. public class Testing {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         HashMap<String,Double> map = new HashMap<String,Double>();  
  6.         ValueComparator bvc =  new ValueComparator(map);  
  7.         TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);  
  8.   
  9.         map.put("A",99.5);  
  10.         map.put("B",67.4);  
  11.         map.put("C",67.4);  
  12.         map.put("D",67.3);  
  13.   
  14.         System.out.println("unsorted map: "+map);  
  15.   
  16.         sorted_map.putAll(map);  
  17.   
  18.         System.out.println("results: "+sorted_map);  
  19.     }  
  20. }  
  21.   
  22. class ValueComparator implements Comparator<String> {  
  23.   
  24.     Map<String, Double> base;  
  25.     public ValueComparator(Map<String, Double> base) {  
  26.         this.base = base;  
  27.     }  
  28.   
  29.     // Note: this comparator imposes orderings that are inconsistent with equals.      
  30.     public int compare(String a, String b) {  
  31.         if (base.get(a) >= base.get(b)) {  
  32.             return -1;  
  33.         } else {  
  34.             return 1;  
  35.         } // returning 0 would merge keys  
  36.     }  
  37. }  


 输出结果

[java]  view plain  copy
  1. unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4}  
  2.   results: {D=67.3, B=67.4, C=67.4, A=99.5}  


2.HashMap按值进行排序

[java]  view plain  copy
  1. public class MapUtil  
  2. {  
  3.     public static <K, V extends Comparable<? super V>> Map<K, V>   
  4.         sortByValue( Map<K, V> map )  
  5.     {  
  6.         List<Map.Entry<K, V>> list =  
  7.             new LinkedList<Map.Entry<K, V>>( map.entrySet() );  
  8.         Collections.sort( list, new Comparator<Map.Entry<K, V>>()  
  9.         {  
  10.             public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )  
  11.             {  
  12.                 return (o1.getValue()).compareTo( o2.getValue() );  
  13.             }  
  14.         } );  
  15.   
  16.         Map<K, V> result = new LinkedHashMap<K, V>();  
  17.         for (Map.Entry<K, V> entry : list)  
  18.         {  
  19.             result.put( entry.getKey(), entry.getValue() );  
  20.         }  
  21.         return result;  
  22.     }  
  23. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值