|
文章目录JavaStream流List转换Map方法汇总合集(大概是最全吧)List->Map>示例一示例二List->MapList->MaptoMap()无重复key示例一示例二toMap()有重复key示例一示例二toMap()空指针异常解决办法一解决办法二解决办法三List->Map>groupingBy()partitioningBy()JavaStream流List转换Map方法汇总合集(大概是最全吧)本文主要介绍Java中利用Stream流将List类型数据转换成Map类型的几种方法整合汇总,其中包含了toMap()、groupingBy()、partitioningBy()等方法的使用,建议收藏方便查阅,如果有帮助到您,不要吝啬点赞、收藏!tips:本文没有推荐使用三方类库提供的List转Map工具类方法,因为在博主公司引入三方依赖需要在评审时说出引用原因,哈哈哈(太麻烦),当然有很多好用三方工具类可以直接完成List转Map的操作,如有需要,后续博主会单独写一篇三方类库的List转Map工具类方法博文提供给大家。💗💗💗您的点赞、收藏、评论是博主输出优质文章的的动力!!!💗💗💗以下示例会覆盖工作中绝大部分的使用场景,如有没有覆盖到的场景,后续会基于本文持续更新!!所以大家一定要收藏!点赞!欢迎在评论区与博主沟通交流!!👇🏻👇🏻👇🏻List->Map>示例一通过Stream流完成转换: @TestpublicvoidtestList1(){Listlist=Arrays.asList("s1:01","s2:02","s3:03","s4:04")atternDELIMITER=Pattern.compile(":");Map>map=list.stream().map(DELIMITER::split).collect(Collectors.groupingBy(a->a[0],Collectors.mapping(a->a[1],Collectors.toList())));System.out.println(JSONObject.toJSONString(map));}123456789运行结果:示例二通过forEach循环转换:@TestpublicvoidtestList1(){Listlist=Arrays.asList("s1:01","s2:02","s3:03","s4:04");Map>map=newHashMap();list.forEach(location->{String[]strArr=location.split(":");map.compute(strArr[0],(country,codes)->{codes=codes==null?newHashSet():codes;codes.add(strArr[1]);returncodes;});});System.out.println(JSONObject.toJSONString(map));}1234567891011121314运行结果:List->MapList->Map代码示例(本示例是存在重复key,并且会以首个出现的key去覆盖后面出现的冲突key): @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(1,2,3,4,4,5,6,7,8);Mapcollect=list.stream().collect(Collectors.toMap(k->k,v->v,(k1,k2)->k1));System.out.println("collect:"+collect);}123456toMap()无重复key示例一List泛型为Student对象,示例需要将name属性作为key,age属性作为value;@TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,Student::getAge));System.out.println(JSONObject.toJSONString(collect));}123456789示例二List泛型为Student对象,示例需要将name属性作为key,Student对象作为value;@TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,student->student));System.out.println(JSONObject.toJSONString(collect));}123456789运行结果:toMap()有重复key当存在重复key时,编译器会报错:java.lang.IllegalStateExceptionuplicatekeyxxxx;出现这种情况就需要在toMap()方法中指定key来避免冲突;示例一解决办法:使用第一个key覆盖第二个key;@TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),2),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,student->student,(key1,key2)->key1));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果(保留了“num”:11的对象):示例二解决办法:使用第二个key覆盖第一个key; @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),2),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,student->student,(key1,key2)->key2));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果(保留了“num”:2的对象):toMap()空指针异常当value为空时,使用toMap()方法进行转换,编译器会抛出java.lang.NullPointerException; @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29),newStudent("小田",null,DateUtil.parse("2007-02-2122:18:56"),null));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,Student::getAge));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果:解决办法一转换时增加判断,如果是null,则设置默认值; @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29),newStudent("小田",null,DateUtil.parse("2007-02-2122:18:56"),null));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,s->s.getAge()==null?-1:s.getAge()));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果:解决办法二使用Optional对值进行包装(和方式一大同小异,就是换了个写法): @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29),newStudent("小田",null,DateUtil.parse("2007-02-2122:18:56"),null));Mapcollect=list.stream().collect(Collectors.toMap(Student::getName,s->Optional.ofNullable(s.getAge()).orElse(-1)));System.out.println("Optional:"+JSONObject.toJSONString(collect));}12345678910运行结果:解决办法三使用collect(Suppliersupplier,BiConsumeraccumulator,BiConsumercombiner)来构建,可允许null值的出现: @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29),newStudent(null,12,DateUtil.parse("2007-02-2122:18:56"),null));HashMapcollect=list.stream().collect(HashMap::new,(obj,v)->obj.put(v.getAge(),v.getName()),HashMap::putAll);System.out.println("collect:"+collect);}12345678910运行结果:List->Map>groupingBy()直接根据一个字段或者属性分组也可以直接用groupingBy()方法: @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),2),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Map>collect=list.stream().collect(Collectors.groupingBy(Student::getName));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果:partitioningBy()partitioningBy()可以理解为特殊的groupingBy(),key值为Boolean类型: @TestpublicvoidtestList2(){Listlist=Lists.newArrayList(newStudent("小张",17,DateUtil.parse("2006-10-0315:18:56"),11),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),5),newStudent("小李",15,DateUtil.parse("2008-03-1902:18:56"),2),newStudent("小王",16,DateUtil.parse("2007-02-2122:18:56"),29));Map>collect=list.stream().collect(Collectors.partitioningBy(s->s.getNum()>=5));System.out.println(JSONObject.toJSONString(collect));}12345678910运行结果:感谢各位大佬的阅读,随手点赞,日薪过万~!!!
|
|