java8 对象转 Map 时 key Duplicate key

308 阅读1分钟

报错信息:

Duplicate key SpotDiffBudgetDTO

java.lang.IllegalStateException: Duplicate key...

问题代码:

Map<String, SpotDiffBudgetDTO> spotMap = list.stream().collect(Collectors
    .toMap(SpotDiffBudgetDTO::getSpotId, 
    spotDiffBudgetDTO -> spotDiffBudgetDTO));

原因解析:

生成Map的key时重复,导致错误,key冲突(因为Map的key必须保持唯一性!)

解决方案:

转换时使用另外一种写法,当遇到key冲突时选取第一个获第二个做key

代码:

case1:
Map<String, SpotDiffBudgetDTO> spotMap = list.stream().collect(Collectors
    .toMap(SpotDiffBudgetDTO::getSpotId,
        item->item,
        (k1,k2) ->k1));

case2:
Map<String, SpotDiffBudgetDTO> spotMap = list.stream().collect(Collectors
    .toMap(SpotDiffBudgetDTO::getSpotId,
        spotDiffBudgetDTO -> spotDiffBudgetDTO,
        (getSpotId,spotDiffBudgetDTO) ->getSpotId));

源码:

 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);
    }

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

参考:blog.csdn.net/TP89757/art…