有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    不使用任何外部库,您只需从entrySet创建一个List,然后使用老式的for-with-index循环在列表上循环:

    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();
    }
    

    根据映射的大小,这种方法将产生更好的性能,因为下一个条目的查找是O(1),而List的创建是O(n),从而导致O(n)的总体复杂性。其中NavigableMap.higherKey()函数为O(log(n)),导致总复杂度为O(n log(n))