Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding item during iteration in java special usecase

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;
    }                   
}
like image 681
RandomDisplayName Avatar asked Jan 26 '26 11:01

RandomDisplayName


2 Answers

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;
}
like image 72
Stephan Hogenboom Avatar answered Jan 28 '26 00:01

Stephan Hogenboom


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

like image 20
DodgyCodeException Avatar answered Jan 28 '26 01:01

DodgyCodeException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!