3
\$\begingroup\$

I have data as follows:

Payment Date  11/01/18  01/01/2019  11/01/09  11/01/20
Total Amount   4536.87     4654.98   4698.63   4687.69

I need to add up all of the Total Amount starting from 11/01/18 through 11/01/20.

For the months in between dates, I need to use the amount from previous month. I also need to change this to account for bi-weekly and semi-monthly.

For example, for month 12/01/2018, I need to use Total Amount from 11/01/18, in this case 4536.87 and so on.

This is what I have so far. Is there a better way to do this?

public void aggretagePaymentAmounts(List<PaymentFields> fieldsType,
            Payments payments, int numberOfTrialPayments){
    AtomicInteger cnt = new AtomicInteger(1);
    Iterator<PaymentFields> fieldsTypeIterator = fieldsType.iterator();
    PaymentFields fieldType = fieldsTypeIterator.next();
    PaymentFields nextFieldType = null;
    if (fieldsTypeIterator.hasNext()) {
        nextFieldType = fieldsTypeIterator.next();
    }

    LocalDate monthDate = LocalDate.parse(fieldType.getPaymentDate());

    while (cnt.getAndIncrement() <= numberOfPayments) {

        monthDate = monthDate.plusMonths(1);
        //what about semi-monthly and bi-weekly?
payments.aggregate(fieldType.getPaymentAmount());

        if (nextFieldType != null) {
            LocalDate nextFieldTypeDate = LocalDate.parse(nextFieldType.getPaymentDate());
            if (nextFieldTypeDate.getMonthValue() == monthDate.getMonthValue()) {
                fieldType = nextFieldType;
                if (fieldsTypeIterator.hasNext()) {
                    nextFieldType = fieldsTypeIterator.next();
                } else {
                    nextFieldType = null;
                }
            }
        }
    }
}

public class Payments {
    private BigDecimal paymentAmount;//getters/setters not shown here

    public void aggregate(BigDecimal tmpPaymentAmount){
        paymentAmount = add(paymentAmount, tmpPaymentAmount);
    }

    private static BigDecimal add(BigDecimal... addends) {
        return Arrays.stream(addends)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }   
}
\$\endgroup\$
  • 1
    \$\begingroup\$ What's with that AtomicInteger? It's a local variable that doesn't escape the method. It seems an int would do. \$\endgroup\$ – Marco Feb 25 '19 at 14:48
  • \$\begingroup\$ @Marco it’s just a convenience incrementor, instead of doing I++ \$\endgroup\$ – Angelina Feb 27 '19 at 1:56
  • 1
    \$\begingroup\$ It doesn't seem very convenient and it already threw one reader off their track. So it made the code more complicated, slower and didn't add any value. Use the common ++ operator instead. \$\endgroup\$ – TorbenPutkonen Feb 27 '19 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.