1

my problem is that I get java.lang.IllegalStateException: Duplicate key every time I try to map a String with List. Is there a way to edit this implementation to somehow handle duplicate keys? Or should I do it in another way?

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;
            }
            ));
developer1
  • 527
  • 4
  • 27

1 Answers1

1

Add a merge function. For example:

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

Since the value of your Map seems to be a function of the key, you can simply return one of the values when you have two values having the the same key.

This is assuming that if two elements of ContractList return the same String for getFeeAccount(), they are equal to each other.

Eran
  • 387,369
  • 54
  • 702
  • 768