java--将Map转换为List并按value值排序输出


代码:

import java.util.*;

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

        Map  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> arrayList = new ArrayList>(map.entrySet());
        Collections.sort(arrayList, new Comparator>() {
            public int compare(Map.Entry map1,
                               Map.Entry map2) {
                return (map2.getValue() - map1.getValue());
            }
        });
        for (Map.Entry 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

代码参考