mirror of
https://gitee.com/dromara/hutool.git
synced 2025-04-05 17:37:59 +08:00
!614 MapUtil.map对null友好,且修复了测试用例中分组问题
Merge pull request !614 from 阿超/v5-dev
This commit is contained in:
commit
8cf462408d
@ -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));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -82,7 +82,7 @@ public class MapUtilTest {
|
||||
// 如你所见,它是一个map,key由用户id,value由用户组成
|
||||
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()));
|
||||
// 如你所见,它是一个map,key由分组id,value由用户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
|
||||
|
Loading…
Reference in New Issue
Block a user