HashMap排序

一、按key值排序
假设HashMap存储的键-值对为(String,Integer),按key排序可以调用JDK函数sort(默认的按字典升序):
[java] view plaincopy
Set<String> keySet = map.keySet(); 
Collections.sort(keySet); 
for(Iterator<String> ite = keySet.iterator(); ite.hasNext();) { 
    String temp = ite.next(); 
    System.out.println("key-value: "+temp+","+map.getValue(temp); 

如果想要按字典的降序排列,则需改写sort方法里面的比较器Comparator: 
Collections.sort(keySet, new Comparator() { 
    public int compare(Object o1, Object o2) { 
       if(Integer.parseInt(o1.toString())>Integer.parseInt(o2.toString()) 
            return 1; 
       if(Integer.parseInt(o1.toString())==Integer.parseInt(o2.toString()) 
           return 0; 
        else 
            return -1; 
    } 
}); 


二、按value值排序
1)方法一:用两个list链表实现
[java] view plaincopy
List<String> keyList = new LinkedList<String>(); 
keyList.addAll(map.keySet()); 
List<Integer> valueList = new LinkedList<Integer>(); 
valueList.addAll(map.values()); 
for(int i=0; i<valueList.size(); i++) 
   for(int j=i+1; j<valueList.size(); j++) { 
      if(valueList.get(j)>valueList.get(i)) { 
          valueList.set(j, valueList.get(i)); 
          valueList.set(i, valueList.get(j)); 
          //同样调整对应的key值 
          keyList.set(j, keyList.get(i)); 
          keyList.set(i, kyeList.get(j)); 
      } 


然后依次把key值和对应value值重新装入HashMap即可。
2)方法二:改写JDK提供的Comparator接口方法compare
[java] view plaincopy
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(); 
list.addAll(map.entrySet()); 
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { 
   public int compare(Map.Entry obj1, Map.Entry obj2) {//从高往低排序 
        
       if(Integer.parseInt(obj1.getValue().toString())<Integer.parseInt(obj2.getValue().toString())) 
           return 1; 
       if(Integer.parseInt(obj1.getValue().toString())==Integer.parseInt(obj2.getValue().toString())) 
           return 0; 
       else 
          return -1; 
   } 
}); 
for(Iterator<Map.Entry<String, Integer>> ite = list.iterator(); ite.hasNext();) { 
     Map.Entry<String, Integer> map = ite.next(); 
    System.out.println("key-value: " + map.getKey() + "," + map.getValue()); 

你可能感兴趣的:(HashMap)