Warm tip: This article is reproduced from stackoverflow.com, please click
arrays for-loop java optimization

Nested for loops optimization

发布于 2020-04-13 09:22:59

Is there a way to optimize the code below:

  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 nested loops all together with a condition look very disturbing. Ultimately there is a need to go over each rate to calculate the premium I couldn`t find a better way to do it.

Questioner
Alisher Urunov
Viewed
48
Alisher Urunov 2020-04-12 17:04

It seems there is no obvious solution here, If loops are necessary here there is no way to get rid of them.