Exception in thread “main“ java.lang.IllegalStateException: Duplicate key xxx
生活随笔
收集整理的這篇文章主要介紹了
Exception in thread “main“ java.lang.IllegalStateException: Duplicate key xxx
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
debug..
hah… 這個錯誤是使用stream流把list收集成map搞的,原因是map的key是唯一的,如果不唯一就拋出了這個異常。
下面是異常代碼
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors;/*** @author echo lovely* @date 2021/9/23 21:16* @description bug demo*/public class Demo {public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("hah");list.add("abc");list.add("hah");// Duplicate key hMap<String, String> collect = list.stream().collect(Collectors.toMap(t -> t, t -> t.substring(0, 1)));System.out.println(collect);} }解決如下:
// 值使用覆蓋前面的鍵的方式, 如果指向front,就不做覆蓋.Map<String, String> collect = list.stream().collect(Collectors.toMap(t -> t, t -> t.substring(0, 1), (front, back) -> back)); System.out.println(collect);總結
以上是生活随笔為你收集整理的Exception in thread “main“ java.lang.IllegalStateException: Duplicate key xxx的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: deepin安装卡死在蓝色背景_求大神帮
- 下一篇: 录音转换成mp3格式