Java8stream操作toMap的key

2023-06-10 10:29:15 浏览数 (1)

准备以下User对象集合 ,构造⽅法User(Long Id, String username)

List userList = new ArrayList<>();

代码语言:javascript复制
    userList.add(new User(1L, "aaa"));

    userList.add(new User(2L, "bbb"));

    userList.add(new User(3L, "ccc"));

    userList.add(new User(2L, "ddd"));

    userList.add(new User(3L, "eee"));

当进⾏普通toMap操作时

Map<Long, String> map = userList.stream()

代码语言:javascript复制
        .collect(Collectors.toMap(User::getId, User::getUsername);

就会报错,说明处理到已存在的key,其对应value为bbb

代码语言:javascript复制
java.lang.IllegalStateException: Duplicate key bbb

 at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)

 at java.util.HashMap.merge(HashMap.java:1253)

 at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)

 at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)

 at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)

 at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)

 at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)

 at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)

 at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)

 at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)

解决⽅式就在Java8提供的Collectors.toMap() ⽅法中,其第三个参数就是当出现 duplicate key的时候的处理⽅案

⽅案⼀: 出现重复时,取前⾯value的值,或者取后⾯放⼊的value值,则覆盖先前的value值

代码语言:javascript复制
Map<Long, String> map = userList.stream()

        .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v1));

Map<Long, String> map = userList.stream()
        .collect(Collectors.toMap(User::getId, User::getUsername, (v1, v2) -> v2));

0 人点赞