0
点赞
收藏
分享

微信扫一扫

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顺序排列的

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

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

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

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

使用新的方式

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

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

 

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


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

作者:翎野君

如果您喜欢或希望看到更多我的文章,可关注我的微信公众号《翎野君》。

转载文章请务必保留出处和署名,否则保留追究法律责任的权利。




举报

相关推荐

0 条评论