Java8 Lambada 将List<T> 转 Map<key, List<T>>

lambada可以用Collectors.toMap 很方便的将List<T> 转为 Map<key ,t> 如下

    @Test
    void testDuplicateKey() {
        Map<Integer, String> map = listDuplicateKey.stream()
                .collect(Collectors.toMap(User::getName, Function.identity(), (oldValue, newValue) -> newValue));
    }

但这碰到重复的key只能将新的对象替代,如果要把重复的key变为数组,并不能满足需求,先有代码如下,但这并不够优雅

@Test
void testList2Mapv1
Map<String, List<User>> map = list.stream().collect(Collectors.toMap(User::getId,
e -> new ArrayList<>(Arrays.asList(new User(e.getName(), e.getColor()))),
(List<User> oldList, List<User> newList) -> {
                    oldList.addAll(newList);
                    return oldList;}));

那么

Collectors.groupingBy方法派上用场了
list.stream().collect(Collectors.groupingBy(User::getId, Collectors.mapping(Function.identity(), Collectors.toList())));

 简洁明了的解决~

猜你喜欢

转载自blog.csdn.net/qq_25484769/article/details/121282775