java向前看下一个地图条目
我的数据集是由到期日和金额组成的付款计划。我将这个存储在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();
}
我如何在迭代过程中“向前看”,而不推进迭代
例如,当我处理地图时。输入{2017-03-01,1000}
,我想查找下一个计算截止日期
# 1 楼答案
不使用任何外部库,您只需从
entrySet
创建一个List
,然后使用老式的for-with-index循环在列表上循环:根据映射的大小,这种方法将产生更好的性能,因为下一个条目的查找是
O(1)
,而List
的创建是O(n)
,从而导致O(n)
的总体复杂性。其中NavigableMap.higherKey()
函数为O(log(n))
,导致总复杂度为O(n log(n))