準備如下User對象集合 ,構造方法User(Long Id, String username)java
List<User> userList = new ArrayList<>(); 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操做時lua
Map<Long, String> map = userList.stream() .collect(Collectors.toMap(User::getId, User::getUsername);
就會報錯,說明處理到已存在的key,其對應value爲bbbcode
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值ip
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));
方案二: Map的value能夠儲存一個list,把重複key的值放入list,再存到value中ci
userList.stream().collect(Collectors.toMap(User::getId, e -> Arrays.asList(e.getUsername()), (List<String> oldList, List<String> newList) -> { oldList.addAll(newList); return oldList; }));
....get