1. 程式人生 > >Java Map按鍵(Key)排序和按值(Value)排序

Java Map按鍵(Key)排序和按值(Value)排序

Map排序的方式有很多種,兩種比較常用的方式:按鍵排序(sort by key), 按值排序(sort by value)。


1、按鍵排序
jdk內建的java.util包下的TreeMap<K,V>既可滿足此類需求,向其構造方法 TreeMap(Comparator<? super K> comparator)  傳入我們自定義的比較器即可實現按鍵排序。

Java程式碼 

public class MapSortDemo {  
    public static void main(String[] args) {  
        Map<String, String> map = new TreeMap<String, String>();  
        map.put("KFC", "kfc");  
        map.put("WNBA", "wnba");  
        map.put("NBA", "nba");  
        map.put("CBA", "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;  
    }  
}  
  
//比較器類  
public class MapKeyComparator implements Comparator<String>{  
    public int compare(String str1, String str2) {  
        return str1.compareTo(str2);  
    }  
}  

 2、按值排序
按值排序就相對麻煩些了,貌似沒有直接可用的資料結構能處理類似需求,需要我們自己轉換一下。
Map本身按值排序是很有意義的,很多場合下都會遇到類似需求,可以認為其值是定義的某種規則或者權重。

原理:將待排序Map中的所有元素置於一個列表中,接著使用Collections的一個靜態方法 sort(List<T> list, Comparator<? super T> c) 
來排序列表,同樣是用比較器定義比較規則。排序後的列表中的元素再依次裝入Map,為了肯定的保證Map中元素與排序後的List中的元素的順序一致,使用了LinkedHashMap資料型別。

Java程式碼 

public class MapSortDemo {  
    public static void main(String[] args) {  
        Map<String, String> map = new TreeMap<String, String>();  
        map.put("KFC", "kfc");  
        map.put("WNBA", "wnba");  
        map.put("NBA", "nba");  
        map.put("CBA", "cba");  
        Map<String, String> resultMap = sortMapByValue(map); //按Value進行排序  
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {  
            System.out.println(entry.getKey() + " " + entry.getValue());  
        }  
    }  
      
    /** 
     * 使用 Map按value進行排序 
     * @param map 
     * @return 
     */  
    public static Map<String, String> sortMapByValue(Map<String, String> map) {  
        if (map == null || map.isEmpty()) {  
            return null;  
        }  
        Map<String, String> sortedMap = new LinkedHashMap<String, String>();  
        List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(map.entrySet());  
        Collections.sort(entryList, new MapValueComparator());  
        Iterator<Map.Entry<String, String>> iter = entryList.iterator();  
        Map.Entry<String, String> tmpEntry = null;  
        while (iter.hasNext()) {  
            tmpEntry = iter.next();  
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());  
        }  
        return sortedMap;  
    }  
}  
  
//比較器類  
public class MapValueComparator implements Comparator<Map.Entry<String, String>> {  
    public int compare(Entry<String, String> me1, Entry<String, String> me2) {  
        return me1.getValue().compareTo(me2.getValue());  
    }  
}