HashMap实现升序排序和降序排序

上代码:

import java.util.*;

public class Test7 {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < 5; i++) {//插入随机数
            map.put("a"+i,(int) (Math.random() * 10));
        }

        ArrayList<Map.Entry<String, Integer>> entryArrayList = new ArrayList<>(map.entrySet());
        System.out.print("排序前:");
        for (Map.Entry<String, Integer> entry : entryArrayList) {
            System.out.print(entry.getKey()+"="+entry.getValue()+"      ");
        }

        System.out.println();

        Collections.sort(entryArrayList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue()-o1.getValue();//倒序
            }
        });
        System.out.print("倒序排序后:");
        for (Map.Entry<String, Integer> entry : entryArrayList) {
            System.out.print(entry.getKey()+"="+entry.getValue()+"      ");
        }

        System.out.println();

        Collections.sort(entryArrayList, 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();//正序
            }
        });
        System.out.print("正序排序后:");
        for (Map.Entry<String, Integer> entry : entryArrayList) {
            System.out.print(entry.getKey()+"="+entry.getValue()+"      ");
        }
    }
}

执行结果:
HashMap实现升序排序和降序排序

上一篇:TP5使用Composer安装PhpSpreadsheet类库实现导入导出


下一篇:性能指标:QPS、TPS、RT、吞吐量