最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決使用stream將list轉(zhuǎn)map時,key重復(fù)導(dǎo)致報錯的問題

 更新時間:2021年06月10日 11:03:03   作者:張財華  
這篇文章主要介紹了解決使用stream將list轉(zhuǎn)map時,key重復(fù)導(dǎo)致報錯的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

要將List對象集合轉(zhuǎn)為map集合,可以通過stream流的形式快速實現(xiàn)轉(zhuǎn)換:

//三個Users對象組成一個List集合
List<Users> list = new ArrayList<>();
list.add(Users.builder().userName("11").userId(1).build());
list.add(Users.builder().userName("11").userId(2).build());
list.add(Users.builder().userName("33").userId(3).build());
//將list轉(zhuǎn)map
Map<String, Users> usersMap = list.stream()
    .collect(Collectors.toMap(Users::getUserName, user -> user));
System.out.println(usersMap.get("11"));

但是上述代碼運行后報了異常:

意思為map中出現(xiàn)了重復(fù)的key,也就是說通過上述方法轉(zhuǎn)map時,出現(xiàn)重復(fù)key并不會出現(xiàn)覆蓋的情況,而是再次在map中添加一個重復(fù)的key,導(dǎo)致報錯。

所以通過stream實現(xiàn)list轉(zhuǎn)map時,要實現(xiàn)重復(fù)的key會被覆蓋,可以使用Function.identity()方法:

//三個Users對象組成一個List集合
List<Users> list = new ArrayList<>();
list.add(Users.builder().userName("11").userId(1).build());
list.add(Users.builder().userName("11").userId(2).build());
list.add(Users.builder().userName("33").userId(3).build());
//將list轉(zhuǎn)map,這里是出現(xiàn)重復(fù)key時,覆蓋前一個
Map<String, Users> usersMap = list.stream()
    .collect(Collectors.toMap(Users::getUserName, Function.identity(), (user1, user2) -> user2));
System.out.println(usersMap.get("11"));
//輸出結(jié)果:
edu.nf.ch08.entity.Users@41aaedaa

JDK 8 Stream List轉(zhuǎn)換為Map的duplicate Key異常

Stream List to Map

Stream提供了List轉(zhuǎn)換為Map提供了非常易用的方法:

Collectors.java:

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

其在轉(zhuǎn)換過程中,會拋出異常:

 @Test(expected = IllegalStateException.class)
    public void testStreamMap_duplicateKey() {
        Employee employee = Employee.builder().id(1).age(20).firstName("zhang").build();
        Employee employee1 = Employee.builder().id(2).age(21).firstName("Li").build();
        Employee employee2 = Employee.builder().id(3).age(22).firstName("Li").build();
        Employee employee3 = Employee.builder().id(4).age(23).firstName("Chen").build();
        List<Employee> employees = Lists.newArrayList();
        employees.add(employee);
        employees.add(employee1);
        employees.add(employee2);
        employees.add(employee3);
        Map<String, Integer> dataMap = employees.stream().collect(Collectors.toMap(e -> e.getFirstName(), e -> e.getAge()));
        //Duplicate Key
        Map<Integer, Employee> employeeMap = employees.stream().collect(Collectors.toMap(e->e.getAge(), e->e));
    }

拋出異常信息:

java.lang.IllegalStateException: Duplicate key 21
 at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
 at java.util.HashMap.merge(HashMap.java:1254)
 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:1382)
 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)
 at org.cjf.java.learn.jdk8.StreamTest.testStreamMap_duplicateKey(StreamTest.java:90)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
 at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
 at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
 at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Process finished with exit code 255

如何解決

增加重復(fù)key情況下的沖突處理策略:

 Map<String, Integer> dataMap = employees.stream().collect(Collectors.toMap(e -> e.getFirstName(), e -> e.getAge(), (k1, k2)-> k1));
        Assert.assertThat(dataMap, hasKey("zhang"));
        Assert.assertThat(dataMap, hasKey("Li"));
        Assert.assertThat(dataMap, hasKey("Chen"));
        Assert.assertThat(dataMap.keySet(), hasSize(3));
        Map<Integer, Employee> employeeMap = employees.stream().collect(Collectors.toMap(e->e.getAge(), e->e, (k1, k2) -> k1));
        Assert.assertThat(dataMap.keySet(), hasSize(3));

這里的處理策略是:

(k1, k2) -> k1

總結(jié)

在Collectors.toMap()轉(zhuǎn)換過程中,需要注意一下duplicate key的處理邏輯,需要增加mergeFunction()處理方法。以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家

相關(guān)文章

  • 實戰(zhàn)講解Maven安裝及基本使用詳解

    實戰(zhàn)講解Maven安裝及基本使用詳解

    這篇文章主要介紹了實戰(zhàn)講解Maven安裝及基本使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • JavaEE的進程,線程和創(chuàng)建線程的5種方式詳解

    JavaEE的進程,線程和創(chuàng)建線程的5種方式詳解

    這篇文章主要為大家詳細介紹了JavaEE的進程,線程和創(chuàng)建線程的5種方式,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Netty分布式抽象編碼器MessageToByteEncoder邏輯分析

    Netty分布式抽象編碼器MessageToByteEncoder邏輯分析

    這篇文章主要介紹了Netty分布式抽象編碼器MessageToByteEncoder的抽象邏輯分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-03-03
  • SpringBoot和Vue實現(xiàn)動態(tài)二維碼的示例代碼

    SpringBoot和Vue實現(xiàn)動態(tài)二維碼的示例代碼

    二維碼在現(xiàn)代社交和營銷活動中被廣泛使用,本文主要介紹了SpringBoot和Vue實現(xiàn)動態(tài)二維碼的示例代碼,文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • 關(guān)于java 圖形驗證碼的解決方法

    關(guān)于java 圖形驗證碼的解決方法

    本篇文章小編為大家介紹,在java中,使用圖形驗證碼的解決方法。需要的朋友參考下
    2013-04-04
  • Springboot+Shiro記錄用戶登錄信息并獲取當前登錄用戶信息的實現(xiàn)代碼

    Springboot+Shiro記錄用戶登錄信息并獲取當前登錄用戶信息的實現(xiàn)代碼

    這篇文章主要介紹了Springboot+Shiro記錄用戶登錄信息,并獲取當前登錄用戶信息,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-05-05
  • SpringBoot實現(xiàn)JWT token自動續(xù)期的示例代碼

    SpringBoot實現(xiàn)JWT token自動續(xù)期的示例代碼

    本文主要介紹了SpringBoot實現(xiàn)JWT token自動續(xù)期的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • Java調(diào)用騰訊云短信API接口的實現(xiàn)

    Java調(diào)用騰訊云短信API接口的實現(xiàn)

    這篇文章主要介紹了Java調(diào)用騰訊云短信API接口的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Intellj Idea中的maven工程Java文件顏色不對,未被識別的解決

    Intellj Idea中的maven工程Java文件顏色不對,未被識別的解決

    這篇文章主要介紹了Intellj Idea中的maven工程Java文件顏色不對,未被識別的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Java創(chuàng)建線程的五種寫法總結(jié)

    Java創(chuàng)建線程的五種寫法總結(jié)

    本文主要為大家詳細介紹一下Java實現(xiàn)線程創(chuàng)建的五種寫法,文中的示例代碼講解詳細,對我們學(xué)習(xí)有一定的幫助,感興趣的可以跟隨小編學(xué)習(xí)一下
    2022-08-08

最新評論

宣威市| 奉节县| 疏附县| 城步| 江津市| 波密县| 安平县| 边坝县| 肇源县| 平远县| 赤壁市| 甘谷县| 望谟县| 临桂县| 延津县| 延吉市| 天长市| 准格尔旗| 昌宁县| 出国| 阳东县| 循化| 通江县| 句容市| 梁河县| 固阳县| 临清市| 察哈| 中阳县| 靖安县| 大悟县| 浪卡子县| 津南区| 湘乡市| 白河县| 云龙县| 普定县| 湘乡市| 泊头市| 宜兰市| 孟村|