背景
現在需要對一個有序的手機列表按照品牌進行分組,那么我們使用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()));
本篇文章如有幫助到您,請給「翎野君」點個贊,感謝您的支持。