1. 程式人生 > 其它 >java--將Map轉換為List並按value值排序輸出

java--將Map轉換為List並按value值排序輸出

程式碼:

import java.util.*;

public class Main {
    public static void main(String[] args) {

        Map <String,Integer> map = new LinkedHashMap<>();
        map.put("a", 1);
        map.put("b", 5);
        map.put("c", 9);
        map.put("d", 7);
        map.put("e", 3);
        map.put("f", 2);
        map.put("g", 6);
        map.put("h", 4);

        ArrayList<Map.Entry<String, Integer>> arrayList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(arrayList, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> map1,
                               Map.Entry<String, Integer> map2) {
                return (map2.getValue() - map1.getValue());
            }
        });
        for (Map.Entry<String, Integer> entry : arrayList) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

結果

c 9
d 7
g 6
b 5
h 4
e 3
f 2
a 1

程式碼參考 https://www.cnblogs.com/letters-zhang/p/3655109.html