Java 8 – 怎样对Map排序

来源:互联网 发布:修改软件下载 编辑:程序博客网 时间:2024/06/05 10:47

在Java 8 中使用Stream 例子对一个 Map 进行按照keys或者values排序.

1. 快速入门

  在java 8中按照此步骤对map进行排序.

  1. 将 Map 转换为 Stream
  2. 对其进行排序
  3. Collect and return a new LinkedHashMap (保持顺序)
Map result = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));

P.S 默认情况下, Collectors.toMap 将返回一个 HashMap

2. 按照keys排序

SortByKeyExample.java
package com.mkyong.test;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.stream.Collectors;public class SortByKeyExample {    public static void main(String[] argv) {        Map<String, Integer> unsortMap = new HashMap<>();        unsortMap.put("z", 10);        unsortMap.put("b", 5);        unsortMap.put("a", 6);        unsortMap.put("c", 20);        unsortMap.put("d", 1);        unsortMap.put("e", 7);        unsortMap.put("y", 8);        unsortMap.put("n", 99);        unsortMap.put("g", 50);        unsortMap.put("m", 2);        unsortMap.put("f", 9);        System.out.println("Original...");        System.out.println(unsortMap);        // sort by keys, a,b,c..., and return a new LinkedHashMap        // toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.        Map<String, Integer> result = unsortMap.entrySet().stream()                .sorted(Map.Entry.comparingByKey())                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));        // Not Recommend, but it works.        //Alternative way to sort a Map by keys, and put it into the "result" map        Map<String, Integer> result2 = new LinkedHashMap<>();        unsortMap.entrySet().stream()                .sorted(Map.Entry.comparingByKey())                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));        System.out.println("Sorted...");        System.out.println(result);        System.out.println(result2);    }}

输出

Original...{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}Sorted...{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}

3. 按照values排序

SortByValueExample.java
package com.mkyong.test;package com.mkyong;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.stream.Collectors;public class SortByValueExample {    public static void main(String[] argv) {        Map<String, Integer> unsortMap = new HashMap<>();        unsortMap.put("z", 10);        unsortMap.put("b", 5);        unsortMap.put("a", 6);        unsortMap.put("c", 20);        unsortMap.put("d", 1);        unsortMap.put("e", 7);        unsortMap.put("y", 8);        unsortMap.put("n", 99);        unsortMap.put("g", 50);        unsortMap.put("m", 2);        unsortMap.put("f", 9);        System.out.println("Original...");        System.out.println(unsortMap);        //sort by values, and reserve it, 10,9,8,7,6...        Map<String, Integer> result = unsortMap.entrySet().stream()                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));        //Alternative way        Map<String, Integer> result2 = new LinkedHashMap<>();        unsortMap.entrySet().stream()                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));        System.out.println("Sorted...");        System.out.println(result);        System.out.println(result2);    }}

输出

Original...{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}Sorted...{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}

引用:

  1. How to sort a Map in Java
  2. LinkedHashMap JavaDoc
  3. Collectors.toMap() JavaDoc
  4. More Fun with Wildcards
  5. Collections.sort() signature
  6. Difference between and in Java
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 公司降职降薪员工不同意怎么办 企业因为经营不善要降薪该怎么办 调岗不降薪我该怎么办? 怀孕后强制调岗怎么办 有限公司法人变更后债务怎么办 有限公司法人跑路债务怎么办 网上买票身份信息待核验怎么办 微信买票身份核验失败怎么办 买高铁票待核验怎么办 网上购票身份待核验怎么办 b站稿件版权原因怎么办 已离职老板打电话说账有问题怎么办 开到应急刹车道怎么办 自动挡的车刹车失灵怎么办 自动挡的车如果刹车失灵怎么办 手动挡汽车刹车失灵怎么办 车辆没有年检出了交通事故怎么办 跟着大货车闯了红灯怎么办 在万家金服买的电子产品坏了怎么办 汽车被油笔画了怎么办? 挂到别人车跑了怎么办 浪琴手表保修卡掉了怎么办 事故车辆维修和报废怎么办 4.2货车拉缸了怎么办 工作中与同事发生矛盾怎么办 和领导关系闹僵怎么办 内倒窗户卡住了怎么办 支付宝存在安全风险怎么办 地铁车站空调坏了怎么办 面试防汛值班发生灾情你怎么办 怀孕上班路途太远怎么办 硕士错过校招应该怎么办 收银员收多了钱怎么办 商铺贷款批不了怎么办 铁路局的门面乱收房租怎么办 酒店夜审房费多过怎么办 夜审房价录多了怎么办 做工地拿不到钱怎么办 赢了官司拿不到钱怎么办 工地上拿不到钱怎么办 做了工拿不到钱怎么办