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

posted @ 2021-09-01 21:15  翎野君  阅读(4663)  评论(0编辑  收藏  举报