zoukankan      html  css  js  c++  java
  • 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/
    若本文如对您有帮助,不妨点击一下右下角的【推荐】。
    如果您喜欢或希望看到更多我的文章,可扫描二维码关注我的微信公众号《翎驿》。
    转载文章请务必保留出处和署名,否则保留追究法律责任的权利。
  • 相关阅读:
    Webpack实现按需打包Lodash的几种方法详解
    一文带你了解babel-preset-env
    Vue-给对象新增属性(使用Vue.$set())
    vue v-slot
    Vue2.4+新增属性.sync、$attrs、$listeners
    彻底搞定Javascript事件循环
    Spring Boot 添加JSP支持【转】
    防火墙设置
    黑黑客客
    tomcat启动时设定环境变量
  • 原文地址:https://www.cnblogs.com/lingyejun/p/15216333.html
Copyright © 2011-2022 走看看