!478 处理了CollStreamUtil.toIdentityMapCollStreamUtil.toMap中,如果value为空时,发生NPE异常问题

Merge pull request !478 from 阿超/v5-dev
This commit is contained in:
Looly 2021-12-08 15:17:42 +00:00 committed by Gitee
commit b1433317fe
2 changed files with 14 additions and 9 deletions

View File

@ -1,6 +1,7 @@
package cn.hutool.core.collection; package cn.hutool.core.collection;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.stream.StreamUtil; import cn.hutool.core.stream.StreamUtil;
@ -48,7 +49,7 @@ public class CollStreamUtil {
return Collections.emptyMap(); return Collections.emptyMap();
} }
return StreamUtil.of(collection, isParallel) return StreamUtil.of(collection, isParallel)
.collect(Collectors.toMap(key, Function.identity(), (l, r) -> l)); .collect(HashMap::new, (HashMap<K, V> m, V v) -> m.put(Opt.ofNullable(v).map(key).get(), v), HashMap::putAll);
} }
/** /**
@ -81,7 +82,7 @@ public class CollStreamUtil {
if (CollUtil.isEmpty(collection)) { if (CollUtil.isEmpty(collection)) {
return Collections.emptyMap(); return Collections.emptyMap();
} }
return StreamUtil.of(collection, isParallel).collect(Collectors.toMap(key, value, (l, r) -> l)); return StreamUtil.of(collection, isParallel).collect(HashMap::new, (HashMap<K, V> m, E v) -> m.put(key.apply(v), value.apply(v)), HashMap::putAll);
} }

View File

@ -6,13 +6,7 @@ import lombok.ToString;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList; import java.util.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* CollectionStream测试方法 * CollectionStream测试方法
@ -34,6 +28,11 @@ public class CollStreamUtilTest {
Assert.assertEquals(map.get(2L).getName(), "李四"); Assert.assertEquals(map.get(2L).getName(), "李四");
Assert.assertEquals(map.get(3L).getName(), "王五"); Assert.assertEquals(map.get(3L).getName(), "王五");
Assert.assertNull(map.get(4L)); Assert.assertNull(map.get(4L));
// 测试value为空时
list.add(null);
map = CollStreamUtil.toIdentityMap(list, Student::getStudentId);
Assert.assertNull(map.get(4L));
} }
@Test @Test
@ -51,6 +50,11 @@ public class CollStreamUtilTest {
Assert.assertEquals(map.get(2L), "李四"); Assert.assertEquals(map.get(2L), "李四");
Assert.assertEquals(map.get(3L), "王五"); Assert.assertEquals(map.get(3L), "王五");
Assert.assertNull(map.get(4L)); Assert.assertNull(map.get(4L));
// 测试value为空时
list.add(new Student(1, 1, 4, null));
map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName);
Assert.assertNull(map.get(4L));
} }
@Test @Test