【问题标题】:Handle duplicating keys while mapping [duplicate]映射时处理重复键[重复]
【发布时间】:2019-12-12 17:03:05
【问题描述】:

我的问题是每次我尝试用List 映射String 时都会得到java.lang.IllegalStateException: Duplicate key。有没有办法编辑这个实现以某种方式处理重复的键?或者我应该用其他方式吗?

Map<String, List<Fee>> feeAccountMap = ContractList
            .stream()
            .filter(o -> !o.getStatus().equals(ContractStatus.CLOSED))
            .collect(Collectors.toMap(o -> o.getFeeAccount(), o -> {
                List<Fee> monthlyFees;
                try {
                    monthlyFees = contractFeeService.getContractMonthlyFees(o);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return monthlyFees;
            }
            ));

【问题讨论】:

    标签: java java-8 duplicates mapping


    【解决方案1】:

    添加合并功能。例如:

    Map<String, List<Fee>> feeAccountMap = ContractList
                .stream()
                .filter(o -> !o.getStatus().equals(ContractStatus.CLOSED))
                .collect(Collectors.toMap(o -> o.getFeeAccount(), o -> {
                    List<Fee> monthlyFees;
                    try {
                        monthlyFees = contractFeeService.getContractMonthlyFees(o);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    return monthlyFees;
                }, (value1, value2) -> value1
                ));
    

    由于您的 Map 的值似乎是键的函数,因此当您有两个具有相同键的值时,您可以简单地返回其中一个值。

    这是假设如果ContractList 的两个元素为getFeeAccount() 返回相同的String,则它们彼此相等。

    【讨论】:

      猜你喜欢
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多