前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java8中使用groupingBy分组返回有序的Map

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

作者头像
翎野君
发布2023-05-12 20:21:08
1.1K0
发布2023-05-12 20:21:08
举报
文章被收录于专栏:翎野君翎野君

背景

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

代码语言:javascript
复制
LinkedHashMap<String,List<Mobile>> linkedHashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand, LinkedHashMap::new,Collectors.toList()));

代码如下

代码语言:javascript
复制
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分组后得到的结果是无序的

代码语言:javascript
复制
Map<String,List<Mobile>> hashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand));

使用新的方式

代码语言:javascript
复制
LinkedHashMap<String,List<Mobile>> linkedHashMap = mobileList.stream().collect(Collectors.groupingBy(Mobile::getBrand, LinkedHashMap::new,Collectors.toList()));
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-09-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
  • 代码如下
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档