adding item during iteration in java special usecase

79 Views Asked by At

I've got a function that should return a list of dates (java.sql.Date) based within a range set as startDate - endDate. I first added the startDate and want to increment it (either +1 day, week or month), and then keep going from the "newest" date until reaching the endDate.

I've tried using a traditional foreach which does not work as it doesn't allow adding new dates while iterating, so I switched to ListIterator. This only goes into while once, increments the date, adds it but then apparently doesn't have a next because the add function doesn't append the item at the end(?)

What would be a practical way to solve this task?

public List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {

    List<Date> dates = new ArrayList<Date>();
    dates.add(startDate);
    ListIterator<Date> iter = dates.listIterator();         
    while(iter.hasNext()) {
        LocalDate new = iter.next().toLocalDate();
        Date newDate;
        if(isDaily) {
            newDate= Date.valueOf(new.plusDays(1));
        } else if(isWeekly) {
            newDate= Date.valueOf(new.plusWeeks(1));
        } else {
            newDate= Date.valueOf(new.plusMonths(1));
        }
        if(newDate.before(endDate) || newDate.equals(endDate) {
            iter.add(newDate);
        } else {
            return dates;
    }                   
}
2

There are 2 best solutions below

1
Stephan Hogenboom On BEST ANSWER

Why do you want to do the while loop based on an Iterator? Would it not be more logical to base it on just the date check you do during the iteration?

  public static List<Date> getBookingDatesInRange(Date startDate, Date endDate, boolean isDaily, boolean isWeekly) {

  List<Date> dates = new ArrayList<>();
  dates.add(startDate);
  Date newDate = startDate;
  while(newDate.before(endDate) || newDate.equals(endDate)) {

    if(isDaily) {
       newDate = Date.valueOf(newDate.toLocalDate().plusDays(1));
    } else if(isWeekly) {
         newDate = Date.valueOf(newDate.toLocalDate().plusWeeks(1));
    } else {
      newDate = Date.valueOf(newDate.toLocalDate().plusMonths(1));
    }
    dates.add(newDate);
    }
  }
  return dates;
}
0
DodgyCodeException On

Use ListIterator::nextIndex() when adding a new item, and then reset the iterator variable to ArrayList::listIterator(int index).