Java - Map排序 - 根据value大小排序

Java - Map排序 - 根据value大小排序

摘要

Java - Map排序 - 根据value大小排序

Map排序

package demo.test_echarts;


import java.util.*;

public class test_map {

    public static void main(String[] args) {


        Map<String, Integer> map = new LinkedHashMap<String, Integer>();
        map.put("A", 20);
        map.put("B", 10);
        map.put("C", 40);
        map.put("D", 30);

        //将Map转化为List集合,List采用ArrayList
        List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        //通过Collections.sort(List I,Comparator c)方法进行排序
        Collections.sort(list_Data, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o1.getValue() - o2.getValue());//  升序方式排序
            }
        });


        //打印结果
        for (int i = 0; i < list_Data.size(); i++) {
            Map.Entry<String, Integer> entry = list_Data.get(i);
            System.out.println("k:" + entry.getKey() + "==>" + " v:" + entry.getValue());
        }

        //打印结果
        System.out.println("==========");
        map.clear();
        for (int i = 0; i < list_Data.size(); i++) {
            map.put(list_Data.get(i).getKey(), list_Data.get(i).getValue());
        }

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("k:" + entry.getKey() + "==>" + " v:" + entry.getValue());
        }

    }

}

输出结果

k:B==> v:10
k:A==> v:20
k:D==> v:30
k:C==> v:40
==========
k:B==> v:10
k:A==> v:20
k:D==> v:30
k:C==> v:40