1. 程式人生 > >TreeMap根據key進行排序舉例

TreeMap根據key進行排序舉例

1、測試方法

package com.easylinktest.data;

import java.util.Map;
import java.util.TreeMap;

public class MapSortDemo {  
  
    public static void main(String[] args) {  
  
        Map<String, String> map = new TreeMap<String, String>();  
  
        map.put("22", "kfc");  
        map.put("3", "wnba");  
        map.put("1.000000000000000000001", "nba");  
        map.put("1.0001", "cba");  
  
        Map<String, String> resultMap = sortMapByKey(map);    //按Key進行排序  
  
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {  
            System.out.println(entry.getKey() + " " + entry.getValue());  
        }  
    }  
      
    /** 
     * 使用 Map按key進行排序 
     * @param map 
     * @return 
     */  
    public static Map<String, String> sortMapByKey(Map<String, String> map) {  
        if (map == null || map.isEmpty()) {  
            return null;  
        }  
  
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator() 
               );  
  
        sortMap.putAll(map);  
  
        return sortMap;  
    }   
} 

2、比較器
package com.easylinktest.data;
import java.util.Comparator;

public class MapKeyComparator implements Comparator<String>{  
    	  
        @Override  
        public int compare(String str1, String str2) {  
        	System.out.println(str1.compareTo(str2)+"*******************");
            return str1.compareTo(str2);  
        }  
    }
結果:

0*******************
1*******************
1*******************
1*******************
2*******************
1*******************
1.000000000000000000001 nba
1.0001 cba
22 kfc
3 wnba