首先假定有以下测试实体类:
@Data@AllArgsConstructorpublicclassTest{privateStringname;privateIntegerage;}一. 出现重复键
如果转换为map后可能出现重复键, 默认会抛出异常, 需指定合并策略.
List<Test>list=newArrayList<>();list.add(newTest("A",20));list.add(newTest("B",30));list.add(newTest("A",40));Map<String,Integer>map1=list.stream().collect(Collectors.toMap(Test::getName,Test::getAge));//报错: java.lang.IllegalStateException: Duplicate key 20Map<String,Integer>map2=list.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)->n));//结果为: {A=40, B=30}二. 出现null的值
如果转换为map后可能出现null的值, 会抛出异常, 需先过滤掉null值.
List<Test>list=newArrayList<>();list.add(newTest("A",20));list.add(newTest("B",30));list.add(newTest("C",null));Map<String,Integer>map1=list.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)->n));//报错: java.lang.NullPointerExceptionMap<String,Integer>map2=list.stream().filter(test->Objects.nonNull(test.getAge())).collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)->n));//结果为: {A=20, B=30}三. 出现null的键
如果转换为map后可能出现null的键, 不会抛出异常.
List<Test>list=newArrayList<>();list.add(newTest("A",20));list.add(newTest("B",30));list.add(newTest(null,40));Map<String,Integer>map=list.stream().collect(Collectors.toMap(Test::getName,Test::getAge,(o,n)->n));//结果为: {null=40, A=20, B=30}引申
Collectors.groupingBy方法如果结果可能出现null的键, 会抛异常, 需要与Collectors.toMap区分.
List<Test>list=newArrayList<>();list.add(newTest("A",20));list.add(newTest("B",30));list.add(newTest(null,40));Map<String,List<Test>>map1=list.stream().collect(Collectors.groupingBy(Test::getName));//报错: java.lang.NullPointerException: element cannot be mapped to a null key//如需要null键的分组, 可使用Optional包装.Map<Optional<String>,List<Test>>map2=list.stream().collect(Collectors.groupingBy(test->Optional.ofNullable(test.getName())));//结果: {Optional.empty=[Test(name=null, age=40)], Optional[A]=[Test(name=A, age=20)], Optional[B]=[Test(name=B, age=30)]}