mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
处理Collectors遇到null的情况
This commit is contained in:
parent
8af05e0892
commit
9538041ac5
@ -2,6 +2,7 @@ package cn.hutool.core.stream;
|
||||
|
||||
import cn.hutool.core.lang.Opt;
|
||||
import cn.hutool.core.text.StrUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
@ -9,6 +10,7 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.BinaryOperator;
|
||||
@ -104,7 +106,10 @@ public class CollectorUtil {
|
||||
final BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
|
||||
final K key = Opt.ofNullable(t).map(classifier).orElse(null);
|
||||
final A container = m.computeIfAbsent(key, k -> downstreamSupplier.get());
|
||||
downstreamAccumulator.accept(container, t);
|
||||
if (ArrayUtil.isArray(container) || Objects.nonNull(t)) {
|
||||
// 如果是数组类型,不需要判空,场景——分组后需要使用:java.util.stream.Collectors.counting 求null元素个数
|
||||
downstreamAccumulator.accept(container, t);
|
||||
}
|
||||
};
|
||||
final BinaryOperator<Map<K, A>> merger = mapMerger(downstream.combiner());
|
||||
@SuppressWarnings("unchecked") final Supplier<Map<K, A>> mangledFactory = (Supplier<Map<K, A>>) mapFactory;
|
||||
|
@ -153,7 +153,7 @@ public class CollStreamUtilTest {
|
||||
// 对null友好
|
||||
final Map<Long, Map<Long, Student>> termIdClassIdStudentMap = CollStreamUtil.group2Map(Arrays.asList(null, new Student(2, 2, 1, "王五")), Student::getTermId, Student::getClassId);
|
||||
final Map<Long, Map<Long, Student>> termIdClassIdStudentCompareMap = new HashMap<Long, Map<Long, Student>>() {{
|
||||
put(null, MapUtil.of(null, null));
|
||||
put(null, MapUtil.empty());
|
||||
put(2L, MapUtil.of(2L, new Student(2, 2, 1, "王五")));
|
||||
}};
|
||||
Assert.assertEquals(termIdClassIdStudentCompareMap, termIdClassIdStudentMap);
|
||||
@ -215,7 +215,7 @@ public class CollStreamUtilTest {
|
||||
new Student(1, 2, 1, "李四"));
|
||||
final Map<Long, List<Student>> termIdStudentsMap = CollStreamUtil.groupBy(students, Student::getTermId, Collectors.toList());
|
||||
final Map<Long, List<Student>> termIdStudentsCompareMap = new HashMap<>();
|
||||
termIdStudentsCompareMap.put(null, Arrays.asList(null, null));
|
||||
termIdStudentsCompareMap.put(null, Collections.emptyList());
|
||||
termIdStudentsCompareMap.put(1L, Arrays.asList(new Student(1L, 1, 1, "张三"), new Student(1L, 2, 1, "李四")));
|
||||
Assert.assertEquals(termIdStudentsCompareMap, termIdStudentsMap);
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user