有没有一种方法可以优化下面的代码:

  public BigDecimal calculate(Policy policy) {
    BigDecimal total = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN);
    for (PolicyObject policyObject : policy.getPolicyObjects()) {
      for (PolicySubObject policySubObject : policyObject.getPolicySubObjects()) {
        for (Risk risk : policySubObject.getRisks()) {
          for (Rate rate : risk.getRates()) {
            // CompareTo returns -1 if BigDecimal is smaller then to compared Big decimal
            // 0 if equals and 1 if greater.
            if (policySubObject.getSumInsured().compareTo(rate.getRangeStart()) >= 0
                && policySubObject.getSumInsured().compareTo(rate.getRangeEnd()) < 0) {
              total = total.add(policySubObject.getSumInsured().multiply(rate.getPremiumRate()));
            }
          }
        }
      }
    }
    return total;
  }


4个嵌套循环以及一个条件看上去都很令人不安。最终,需要遍历每个费率以计算出我找不到更好的方法来计算的溢价。

最佳答案

似乎这里没有明显的解决方案,如果这里需要循环,则无法摆脱它们。

10-06 09:37