1. 程式人生 > >如何對map進行排序

如何對map進行排序

Map介紹

常用的Map有HashMap,TreeMap,LinkedHashMap

HashMap:最常用的Map,根據key的HashCode值來儲存資料,根據key可以直接獲取它的Value,具有很快的訪問速度。HashMap最多隻允許一條記錄的key值為null(多條會覆蓋);允許多條記錄的Value為null。非執行緒安全

TreeMap: 根據key排序,預設是按升序排序,也可以指定排序的比較器,遍歷TreeMap時,得到的記錄是排過序的。TreeMap不允許key的值為null。非執行緒安全

LinkedHashMap: 插入順序,遍歷LinkedHashMap時,先得到的記錄肯定是先插入的。繼承HashMap,非執行緒安全

TreeMap排序

TreeMap只能根據key進行排序,TreeMap本身是個二叉樹,元素的順序是由key的值決定的

TreeMap內部預設有個Comparator,在new的時候可以覆蓋預設的Comparator定義自己的排序規則,不過還是隻能根據key進行排序

private static void sortTreeMap(){
    Map<String,String> map =new TreeMap<>((k1,k2)->{
        return k1.compareTo(k2);
    });
    map.put("a"
,"2"); map.put("c","5"); map.put("d","6"); map.put("b","1"); map.forEach((k,v)->{ System.out.println(k+":"+v); }); }

輸出結果

a:2
b:1
c:5
d:6

HashMap排序

HashMap本身是沒有順序的,不能直接對其進行排序

要排序只能先轉成list然後對應list排序後,再轉成LinkedHasHMap

這樣做排序完全由自己定義,既可以多key排序也可以多value排序

private
static void sortMapValue(){ Map<String,String> map =new HashMap<>(); map.put("a","2"); map.put("c","5"); map.put("d","6"); map.put("b","1"); List<Map.Entry<String,String>> lstEntry=new ArrayList<>(map.entrySet()); Collections.sort(lstEntry,((o1, o2) -> { return o1.getValue().compareTo(o2.getValue()); })); lstEntry.forEach(o->{ System.out.println(o.getKey()+":"+o.getValue()); }); //如果一定要返回一個map,就new一個LinkedHashMap,將list中所有值依次put進去就可以 /*LinkedHashMap<String,String> linkedHashMap=new LinkedHashMap<>(); lstEntry.forEach(o->{ linkedHashMap.put(o.getKey(),o.getValue()); });*/ }

輸出結果

b:1
a:2
c:5
d:6