Java Map实现按value排序

如果想按照key来排序,用TreeMap就可以;如果想实现按value排序,可以采用下面这种方式

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("test1",1);
        map.put("test2",2);
        map.put("test3",3);
        map.put("test4",4);
        List<Map.Entry<String,Integer>> mapList = new ArrayList<>(map.entrySet());
        mapList.sort((o1, o2) -> o2.getValue()-o1.getValue());
        for (Map.Entry<String, Integer> entry : mapList) {
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
    }