2012年4月25日 星期三

JAVA的HashMap對value排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class neo {
  //實作Comparator的介面宣告compare方法
   private class ValueComparator implements Comparator<Map.Entry<String, Integer>>  
   {  
      public int compare(Map.Entry<String, Integer> mp1, Map.Entry<String, Integer> mp2)   
      {  
      //大到小mp2-mp1,小到大mp1-mp2
         return mp2.getValue() - mp1.getValue();  
      }  
   }  

   public List<String> showsortedlist(Map<String, Integer> map)
   {
      //先把HashMap轉成List形式
      List<Map.Entry<String, Integer>> sortedlist = new ArrayList<Map.Entry<String, Integer>>(map.size()); 
      //把map中所有東西丟到sortedlist 
      sortedlist.addAll(map.entrySet()); 
      ValueComparator vc = new ValueComparator();  
      //利用Collections.sort排序sortedlist
      Collections.sort(sortedlist, vc); 
      final List<String> sortedvalue_keys = new ArrayList<String>(map.size()); 
      Iterator iter = sortedlist.iterator();
      while (iter.hasNext()) {
         Entry<String, Integer> data = (Entry<String, Integer>) iter.next();
         Object key = data.getKey();
         Object val = data.getValue();
         System.out.println(key+"=>"+val);
         sortedvalue_keys.add((String) key);  
     }
     return sortedvalue_keys;
  }
  public static void main(String args[]){
   Map<String,Integer> map = new HashMap<String,Integer>();  
   map.put("20030120" , new Integer (56));    
   map.put("20030118" , new Integer (19));    
   map.put("20030125" , new Integer (25));    
   map.put("20030122" , new Integer (32));    
   map.put("20030117" , new Integer (67));    
   map.put("20030123" , new Integer (34));    
   map.put("20030124" , new Integer (42));    
   map.put("20030121" , new Integer (19));    
   map.put("20030119" , new Integer (98)); 
   Iterator iter = map.entrySet().iterator();
   while (iter.hasNext()) {
       Map.Entry entry = (Map.Entry) iter.next();
       Object key = entry.getKey();
       Object val = entry.getValue();
       System.out.println(key+"=>"+val);
   } 
   System.out.println("開始排序");
   neo gosort  = new nothing();
   gosort.showsortedlist(map);
 }
}

沒有留言:

張貼留言