Java8中List转map遇到的问题

Java8使用stream的List转map遇到的问题。
首先简单介绍一下Java8的新特性,Lambda表达式。一句话总结一下,就是一个匿名类函数或者叫闭包。他带来的好处是可以动态的去操作我们需要操作的数据结构。
平时开发的时候使用比较多的就是List转Map,比如:

    public static void main(String[] arg){
        List<Test> testList = new ArrayList<>();
        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, test -> test));
    }
    
    @Data
    private static class Test {
        private Integer id;
        private String name;
    }

我创建了一个Test的对象,将Test对象的集合转换成map。但从逻辑上来说,这是一点问题都没有的。
但是测试过后就会发现不对劲,让我们添加几组数据进行测试。

    public static void main(String[] arg){
        List<Test> testList = new ArrayList<>();
        testList.add(new Test(1, "test"));
        testList.add(new Test(2, "test"));
        testList.add(new Test(3, "test"));
        testList.add(new Test(1, "test"));
        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, test -> test));
    }

    @Data
    @AllArgsConstructor
    private static class Test {
        private Integer id;
        private String name;
    }

编译发现,会出现一个很典型的错误。

Exception in thread "main" java.lang.IllegalStateException: Duplicate key FtpUtil.Test(id=1, name=test)

异常说的很清楚,就是转换map的时候出现键值重复,所以需要解决这样一个异常。
直接上代码:

        Map<Integer, Test> testMap = testList.stream().collect(Collectors.toMap(Test::getId, Function.identity(), 
                (test1, test2) -> test1));
    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }

我们用到了Function这个接口, 官方说明的很清楚,返回一个需要使用的数据。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值