0

My data set is a payment schedule consisting of due dates and amounts. I'm storing this in a TreeMap.

Map<LocalDate, BigDecimal> paymentSchedule = new TreeMap<>();
paymentSchedule.put(LocalDate.parse("2017-01-01", formatter), new BigDecimal("1000"));
paymentSchedule.put(LocalDate.parse("2017-02-01", formatter), new BigDecimal("1000"));
paymentSchedule.put(LocalDate.parse("2017-03-01", formatter), new BigDecimal("1000"));
paymentSchedule.put(LocalDate.parse("2017-04-01", formatter), new BigDecimal("1000"));
paymentSchedule.put(LocalDate.parse("2017-05-01", formatter), new BigDecimal("1000"));
paymentSchedule.put(LocalDate.parse("2017-06-01", formatter), new BigDecimal("1000"));

for (Map.Entry<LocalDate, BigDecimal> paymentPeriod : paymentSchedule.entrySet()) {
    LocalDate dueDate = paymentPeriod.getKey();
    BigDecimal amountDue = paymentPeriod.getValue();
}

How can I "peek ahead" during an iteration without advancing the iteration?

For example, when I'm working with the Map.Entry for {2017-03-01,1000}, I want to look up the next due date for a calculation.

Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
A_B
  • 1,009
  • 3
  • 15
  • 37

1 Answers1

0

Without using any external library you could simply create a List from your entrySet and loop over the list using the old fashioned for-with-index loop:

final List<Map.Entry<LocalDate, BigDecimal>> entryList = new ArrayList<>(paymentSchedule.entrySet());
for (int i = 0; i < entryList.size(); i++) {
    Map.Entry<LocalDate, BigDecimal> paymentPeriod = entryList.get(i);
    if (i < entryList.size() - 1) {
        Map.Entry<LocalDate, BigDecimal> nextPaymentPeriod = entryList.get(i + 1);
    }
    LocalDate dueDate = paymentPeriod.getKey();
    BigDecimal amountDue = paymentPeriod.getValue();
}

Depending on the size of your map this approach will yield a better performance as the lookup of the next entry is O(1) and creation of the List is O(n) resulting in an overall complexity of O(n). Where the NavigableMap.higherKey() function is O(log(n)) resulting in a total complexity of O(n log(n)).

dpr
  • 10,591
  • 3
  • 41
  • 71