猿问

映射时处理复制键

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


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;

            }

            ));


缥缈止盈
浏览 102回答 1
1回答

精慕HU

添加合并功能。例如:Map<String, List<Fee>> feeAccountMap = ContractList&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(o -> !o.getStatus().equals(ContractStatus.CLOSED))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(o -> o.getFeeAccount(), o -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Fee> monthlyFees;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; monthlyFees = contractFeeService.getContractMonthlyFees(o);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return monthlyFees;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, (value1, value2) -> value1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ));由于您的值Map似乎是键的函数,因此当您有两个具有相同键的值时,您可以简单地返回其中一个值。这是假设如果 的两个元素ContractList返回相同的Stringfor getFeeAccount(),则它们彼此相等。
随时随地看视频慕课网APP

相关分类

Java
我要回答