java.lang.IllegalStateException: Duplicate key 20


 

這個我在公司遇到的一個問題。原因:
使用Map<String, String> RelationMap = relation.stream().collect(Collectors.toMap(s -> s[2], s -> s[1], (oldValue, newValue) -> newValue)))
轉換過程中出現重復的Key。導致有多個value程序不知道應該取哪個的問題。

正常案例

老師跟班級之間的關系,每一個老師都負責一個班級。

 1 @Data
 2 public class TeacherClass {
 3 
 4     /**主鍵ID*/
 5     private int id;
 6 
 7     /**教師ID*/
 8     private int teachId;
 9 
10     /**班級ID*/
11     private int classId;
12 
13     public TeacherClass(int id, int teachId, int classId) {
14         this.id = id;
15         this.teachId = teachId;
16         this.classId = classId;
17     }
18 }

 


老師與班級的關系

實際應用代碼

 1 //查詢所有老師負責的班級(一個老師對應一個班級)
 2         List<TeacherClass> list = new ArrayList<>(20);
 3         int count = 10;
 4         for (int i = 0; i < count; i++) {
 5             list.add(new TeacherClass(i, 100 + i, 200 + i));
 6         }
 7 
 8         //結果返回每個老師對應的班級ID
 9         Map<Integer, Integer> collect = list.stream().collect(Collectors.toMap(TeacherClass::getTeachId, TeacherClass::getClassId));
10         System.out.println("老師負責的班級ID:" + collect);

 



執行結果如下

顯然是OK的

 

錯誤案例

假設這個時候程序出了一個bug, 導致有一個老師負責兩個班級。那么再執行之前的代碼會有什么問題呢?

 

 1         //查詢所有老師負責的班級(一個老師對應一個班級)
 2         List<TeacherClass> list = new ArrayList<>(20);
 3         int count = 10;
 4         for (int i = 0; i < count; i++) {
 5             list.add(new TeacherClass(i, 100 + i, 200 + i));
 6         }
 7 
 8         //程序出了一個bug,導致有一個老師負責兩個班級
 9         list.add(new TeacherClass(50, 100, 300));
10 
11         //結果返回每個老師對應的班級ID
12         Map<Integer, Integer> collect = list.stream().collect(Collectors.toMap(TeacherClass::getTeachId, TeacherClass::getClassId));
13         System.out.println("老師負責的班級ID:" + collect);

 

 

執行結果如下

 

顯然是有問題的。原因就是出現了重復的Key, 那么怎么解決呢?
很簡單,將Collectors.toMap(TeacherClass::getTeachId, TeacherClass::getClassId) 替換為Collectors.toMap(TeacherClass::getTeachId, TeacherClass::getClassId, (aLong, aLong2) -> aLong2 >= aLong ? aLong2 : aLong);

 

(aLong, aLong2) -> aLong2 >= aLong ? aLong2 : aLong表示的是出現重復Key的執行邏輯,如果出現重復Key取最大的value。具體邏輯可以自己定義

 

 

實際應用代碼

 

 1 //查詢所有老師負責的班級(一個老師對應一個班級)
 2         List<TeacherClass> list = new ArrayList<>(20);
 3         int count = 10;
 4         for (int i = 0; i < count; i++) {
 5             list.add(new TeacherClass(i, 100 + i, 200 + i));
 6         }
 7 
 8         //程序出了一個bug,導致有一個老師負責兩個班級
 9         list.add(new TeacherClass(50, 100, 300));
10 
11         //結果返回每個老師對應的班級ID
12         Map<Integer, Integer> collect = list.stream().collect(Collectors.toMap(TeacherClass::getTeachId, TeacherClass::getClassId
13                 , (aLong, aLong2) -> aLong2 >= aLong ? aLong2 : aLong));
14         System.out.println("老師負責的班級ID:" + collect);

 

 

 

至此問題就解決了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM