LinkedHashMap排序

LinkedHashMap map = new LinkedHashMap<>();

//先转成ArrayList集合
ArrayList> list = 
        new ArrayList>(map.entrySet());

//从小到大排序(从大到小将o1与o2交换即可)
Collections.sort(list, new Comparator>() {

    @Override
    public int compare(Entry o1, Entry o2) {
        return ((o1.getValue() - o2.getValue() == 0) ? 
                0: (o1.getValue() - o2.getValue() > 0) ? 1: -1);
    }

});

//新建一个LinkedHashMap,把排序后的List放入
LinkedHashMap map2 = new LinkedHashMap<>();
for (Map.Entry entry : list) {
    map2.put(entry.getKey(), entry.getValue());
}

//遍历输出
for (Map.Entry entry : map2.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}

你可能感兴趣的:(java开发)