SoFunction
Updated on 2025-04-11

Solve: Duplicate key exception problem

:Duplicate key exception

Use scenarios

In actual application development, a List query data collection is often converted into a map. So ().collect() here actually does this thing. It is implemented in Java8's stream method. It uses type as key and entity object as value to form a map.

    //Inquiry    List<QuestionCategoryEntity> list = (entityWrapper);
    
    Map<String, String> categoryMap = ().collect(
        (
            QuestionCategoryEntity::getCategoryCode,
            QuestionCategoryEntity::getCategoryName
        )
    );

In some business scenarios, the following exceptions will appear: Duplicate key, map key duplication, as shown in the above QuestionCategoryEntity::getCategoryCode.

: Duplicate key special examination
    at $throwingMerger$0(:133)
    at (:1245)
    at $toMap$58(:1320)
    at $(:169)
    at $(:1374)
... ...

Solution

Use the overloaded method of toMap(), and if it already exists, it will not be modified, and use the previous data directly.

    //Inquiry    List<QuestionCategoryEntity> list = (entityWrapper);
    
    Map<String, String> categoryMap = ().collect(
        (
            QuestionCategoryEntity::getCategoryCode,
            QuestionCategoryEntity::getCategoryName,
            (entity1, entity2) -> entity1
        )
    );

Equivalent to

(entityWrapper);
    
    Map<String, String> categoryMap = ().collect(
        (
            QuestionCategoryEntity::getCategoryCode,
            QuestionCategoryEntity::getCategoryName,
            (entity1, entity2) {
            	return entity1
            }
        )
    );

(entity1, entity2) -> entity1 The arrow function used here, that is, when duplicate key data appears, this method will be called back. You can handle duplicate key data in this method. The editor here is roughly pointing to use the previous data directly.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.