• java8中使用groupingBy分组返回有序的Map


    背景

    现在需要对一个有序的手机列表按照品牌进行分组,那么我们使用java8中的groupingBy的时候默认返回的是无序的Map,如果想输出有序的Map,需要使用三参数的groupingBy,指定返回有序的LinkedHashMap 

    LinkedHashMap<String,List<Mobile>> linkedHashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand, LinkedHashMap::new,Collectors.toList()));

    代码如下

    package com.lingyejun.blog;
    
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class MobileMain {
    
        public static void main(String[] args) {
            List<Mobile> mobileList = getMobileList();
            Map<String,List<Mobile>> hashMap = mobileList.stream().collect(Collectors(Mobile::getBrand));
            LinkedHashMap<String,List<Mobile>> linkedHashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand, LinkedHashMap::new,Collectors.toList())); } public static List<Mobile> getMobileList() { Mobile mobile1 = new Mobile("华为Mate40","华为",1); Mobile mobile2 = new Mobile("华为Mate30","华为",2); Mobile mobile3 = new Mobile("小米MIX7","小米",3); Mobile mobile4 = new Mobile("小米11畅玩版","小米",4); Mobile mobile5 = new Mobile("小米11青春版","小米",5); Mobile mobile6 = new Mobile("Iphone11","Iphone",6); Mobile mobile7 = new Mobile("Oppo Reno6","Oppo",7); Mobile mobile8 = new Mobile("Oppo K7x","Oppo",8); return Arrays.asList(mobile1, mobile2, mobile3, mobile4, mobile5, mobile6, mobile7, mobile8); } }

     原始的list是按照sequence顺序排列的

     按照常规的groupingBy分组后得到的结果是无序的

    Map<String,List<Mobile>> hashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand));

    使用新的方式

    LinkedHashMap<String,List<Mobile>> linkedHashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand, LinkedHashMap::new,Collectors.toList()));

    本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

    原文链接:https://www.cnblogs.com/lingyejun/p/15216333.html

    作者:翎野君
    出处:http://www.cnblogs.com/lingyejun/
    若本文如对您有帮助,不妨点击一下右下角的【推荐】。
    如果您喜欢或希望看到更多我的文章,可扫描二维码关注我的微信公众号《翎驿》。
    转载文章请务必保留出处和署名,否则保留追究法律责任的权利。
  • 相关阅读:
    起点中文网小说爬取-etree,xpath,os
    拉勾网爬虫--待改正
    破解有道词典翻译-版本二
    pycharm错误:11001
    自动化selenium 测试之道(一)
    valgrind 详细说明
    sar命令使用详解
    Linux CPU实时监控mpstat命令详解
    Linux IO实时监控iostat命令详解
    RPM安装命令总结
  • 原文地址:https://www.cnblogs.com/lingyejun/p/15216333.html
Copyright © 2020-2023  润新知