leetcode奇技淫巧-Map依據鍵或值排序並輸出

寫在前頭

邏輯解釋

我們知道Arrays.sort(數組),也知道Collections.sort(集合類)的方式來進行排序,其中還有一個自定義的比較器的方式來進行的排序,下面通過匿名內部類的形式實現了,下面通過實現比較器接口,重寫比較方法來實現比較,比較的方法中有兩個參數,o1 表示前面的元素,o2 表示後面的元素,當這個方法返回正數表示前者比後者大,返回負數表示前者比後者小,相等即相當,當我們拿 o1 減去 o2 如果是正數,表示前者大,那麼進行排序默認從小到大;如果 o1 減去 o2 是正數,我們返回負的這個正數,那麼相當於告訴比較器前者比後者小(實際是大),於是按照默認從小到大,大的 o1 就會排到前面,這樣就實現了從大到小的逆序了!

實際應用

我們在 leetcode 刷排序的題目或者數組,字符串的題目會遇到這種類型的題目,模式大概是給一個數組,然後對值排序,但是要你輸出數組下標,當然除了下面的解法外,還有很多其他思路,這裏主要是做一個 map 中對鍵或者值排序的分享

Map 排序 value 輸出 key

public void function(Map<Integer, Integer> map)
    // 新建 map 鍵值對的 list
    List<Map.Entry<Integer,Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
	// 從小到大排序
	Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
        public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
            return o1.getValue() - o2.getValue();
        }
    });
	// value 排好序後,輸出 key 值
	for(Map.Entry<Integer,Integer> mapping : list){
        System.out.println(mapping.getKey());
    }
}

Map 排序 key 輸出 value

public void function(Map<Integer, Integer> map)
    // 新建 map 鍵值對的 list
    List<Map.Entry<Integer,Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
	// 從小到大排序
	Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
        public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
            return o1.getKey() - o2.getKey();
        }
    });
	// key 排好序後,輸出 value 值
	for(Map.Entry<Integer,Integer> mapping : list){
        System.out.println(mapping.getValue());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章