首页 > 代码库 > Map排序

Map排序

HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。 


TreeMap: 能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。 


TreeMap默认按key进行升序排序,如果想改变默认的顺序,可以使用比较器: 

Map<String,String> map = new TreeMap<String,String>(new Comparator<String>(){    public int compare(String obj1,String obj2){       //降序排序       return obj2.compareTo(obj1); 
   } 
});
map.put(
"month", "The month"); map.put("bread", "The bread"); map.put("attack", "The attack"); Set<String> keySet = map.keySet(); Iterator<String> iter = keySet.iterator(); while(iter.hasNext()){ String key = iter.next(); System.out.println(key+":"+map.get(key)); }

 

如果要对TreeMap按照value的值进行排序,或者对HashMap,Hashtable,LinkedHashMap进行排序,则可以使用Map.Entry<K,V>接口结合List实现: 

eg.1 对TreeMap按照value值升序: 

List<Map.Entry<String,String>> mappingList = null; Map<String,String> map = new TreeMap<String,String>(); map.put("aaaa", "month"); map.put("bbbb", "bread"); map.put("ccccc", "attack");   //通过ArrayList构造函数把map.entrySet()转换成list mappingList = new ArrayList<Map.Entry<String,String>>(map.entrySet()); //通过比较器实现比较排序 Collections.sort(mappingList, new Comparator<Map.Entry<String,String>>(){   public int compare(Map.Entry<String,String> mapping1,Map.Entry<String,String> mapping2){       return mapping1.getValue().compareTo(mapping2.getValue());    } });   for(Map.Entry<String,String> mapping:mappingList){    System.out.println(mapping.getKey()+":"+mapping.getValue()); } 

 

eg.2 对HashMap(或Hashtable,LinkedHashMap)按照key的值升序: 

List<Map.Entry<String,String>> mappingList = null; Map<String,String> map = new HashMap<String,String>(); map.put("month", "month"); map.put("bread", "bread"); map.put("attack", "attack");   //通过ArrayList构造函数把map.entrySet()转换成list mappingList = new ArrayList<Map.Entry<String,String>>(map.entrySet()); //通过比较器实现比较排序 Collections.sort(mappingList, new Comparator<Map.Entry<String,String>>(){   public int compare(Map.Entry<String,String> mapping1,Map.Entry<String,String> mapping2){       return mapping1.getKey().compareTo(mapping2.getKey());    } });   for(Map.Entry<String,String> mapping:mappingList){    System.out.println(mapping.getKey()+":"+mapping.getValue()); }

 

Map排序