【弄nèng - 化繁为简】Java8 List<Object>转Map<Integer,List< Object >>

一. Collectors.toMap

看看源码

    public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }

有三个参数,还有个默认参数
参数含义:

- keyMapper:Key 的映射函数
   
- valueMapper:Value 的映射函数
   
- mergeFunction:当 Key 冲突时,调用的处理方法
   
- mapSupplier:Map 构造器,在需要返回特定的 Map 时使用

二. 事例

输入

	public static void main(String[] args) {
        List<TestEntity> testList = Lists.newArrayList(
                new TestEntity().setId(1).setName("张三"),
                new TestEntity().setId(1).setName("李四"), // Key 相同
                new TestEntity().setId(2).setName("王五")
        );

        Map<Integer, String> map = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
        System.out.println("map:" + map);
    }

输出
在这里插入图片描述

三. List转Map<Integer,List< Object >>

输入

    public static void main(String[] args) {
        List<TestEntity> testList = Lists.newArrayList(
                new TestEntity().setId(1).setName("张三"),
                new TestEntity().setId(1).setName("李四"), // Key 相同
                new TestEntity().setId(2).setName("王五")
        );

        Map<Integer, String> map = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
        System.out.println("map:" + map);

        Map<Integer, List<TestEntity>> mapList = testList.stream()
                .collect(Collectors.toMap(TestEntity::getId, item -> {
                    List<TestEntity> list = Lists.newArrayList();
                    list.add(item);
                    return list;
                }, (n1, n2) -> {
                    n1.addAll(n2);
                    return n1;
                }));
        System.out.println("map:" + mapList);
    }

输出
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值