!614 MapUtil.map对null友好,且修复了测试用例中分组问题

Merge pull request !614 from 阿超/v5-dev
This commit is contained in:
Looly 2022-05-09 02:05:21 +00:00 committed by Gitee
commit 8cf462408d
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 5 additions and 3 deletions

View File

@ -6,6 +6,7 @@ import cn.hutool.core.lang.Editor;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
@ -708,7 +709,7 @@ public class MapUtil {
if (null == map || null == biFunction) {
return MapUtil.newHashMap();
}
return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, m -> biFunction.apply(m.getKey(), m.getValue())));
return map.entrySet().stream().collect(CollectorUtil.toMap(Map.Entry::getKey, m -> biFunction.apply(m.getKey(), m.getValue()),(l,r)->l));
}
/**

View File

@ -82,7 +82,7 @@ public class MapUtilTest {
// 如你所见它是一个mapkey由用户idvalue由用户组成
Map<Long, User> idUserMap = Stream.iterate(0L, i -> ++i).limit(4).map(i -> User.builder().id(i).name(customers.poll()).build()).collect(Collectors.toMap(User::getId, Function.identity()));
// 如你所见它是一个mapkey由分组idvalue由用户ids组成典型的多对多关系
Map<Long, List<Long>> groupIdUserIdsMap = groups.stream().flatMap(group -> idUserMap.keySet().stream().map(userId -> UserGroup.builder().groupId(group.getId()).userId(userId).build())).collect(Collectors.groupingBy(UserGroup::getUserId, Collectors.mapping(UserGroup::getGroupId, Collectors.toList())));
Map<Long, List<Long>> groupIdUserIdsMap = groups.stream().flatMap(group -> idUserMap.keySet().stream().map(userId -> UserGroup.builder().groupId(group.getId()).userId(userId).build())).collect(Collectors.groupingBy(UserGroup::getGroupId, Collectors.mapping(UserGroup::getUserId, Collectors.toList())));
// 神奇的魔法发生了 分组id和用户ids组成的map竟然变成了订单编号和用户实体集合组成的map
Map<Long, List<User>> groupIdUserMap = MapUtil.map(groupIdUserIdsMap, (groupId, userIds) -> userIds.stream().map(idUserMap::get).collect(Collectors.toList()));
@ -98,7 +98,8 @@ public class MapUtilTest {
Assert.assertEquals("竹鼠发烧找华农", users.get(2).getName());
Assert.assertEquals("朴实无华朱一旦", users.get(3).getName());
});
// 能写代码真开心
// 对null友好
MapUtil.map(MapUtil.of(0, 0), (k, v) -> null).forEach((k, v) -> Assert.assertNull(v));
}
@Test