java中stream的Collectors.toMap常见踩坑点
首先假定有以下测试实体类:DataAllArgsConstructorpublicclassTest{privateStringname;privateIntegerage;}一. 出现重复键如果转换为map后可能出现重复键, 默认会抛出异常, 需指定合并策略.ListTestlistnewArrayList();list.add(newTest(A,20));list.add(newTest(B,30));list.add(newTest(A,40));MapString,Integermap1list.stream().collect(Collectors.toMap(Test::getName,Test::getAge));//报错: java.lang.IllegalStateException: Duplicate key 20MapString,Integermap2list.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)-n));//结果为: {A40, B30}二. 出现null的值如果转换为map后可能出现null的值, 会抛出异常, 需先过滤掉null值.ListTestlistnewArrayList();list.add(newTest(A,20));list.add(newTest(B,30));list.add(newTest(C,null));MapString,Integermap1list.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)-n));//报错: java.lang.NullPointerExceptionMapString,Integermap2list.stream().filter(test-Objects.nonNull(test.getAge())).collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)-n));//结果为: {A20, B30}三. 出现null的键如果转换为map后可能出现null的键, 不会抛出异常.ListTestlistnewArrayList();list.add(newTest(A,20));list.add(newTest(B,30));list.add(newTest(null,40));MapString,Integermaplist.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)-n));//结果为: {null40, A20, B30}引申Collectors.groupingBy方法如果结果可能出现null的键, 会抛异常, 需要与Collectors.toMap区分.ListTestlistnewArrayList();list.add(newTest(A,20));list.add(newTest(B,30));list.add(newTest(null,40));MapString,ListTestmap1list.stream().collect(Collectors.groupingBy(Test::getName));//报错: java.lang.NullPointerException: element cannot be mapped to a null key//如需要null键的分组, 可使用Optional包装.MapOptionalString,ListTestmap2list.stream().collect(Collectors.groupingBy(test-Optional.ofNullable(test.getName())));//结果: {Optional.empty[Test(namenull, age40)], Optional[A][Test(nameA, age20)], Optional[B][Test(nameB, age30)]}