Search code examples
javaspring-bootiterationlocaldate

DateRange iterating wrong (code taken from SO)


A few months ago I found this thread about iterating over days in java

Java 8 LocalDate - How do I get all dates between two dates?

And started using class DateRange:

public class DateRange implements Iterable<LocalDate> {

    private final LocalDate startDate;
    private final LocalDate endDate;

    public DateRange(LocalDate startDate, LocalDate endDate) {
        //check that range is valid (null, start < end)
        this.startDate = startDate;
        this.endDate = endDate;
    }

    @Override
    public Iterator<LocalDate> iterator() {
        return stream().iterator();
    }

    public Stream<LocalDate> stream() {
        return Stream.iterate(startDate, d -> d.plusDays(1))
                .limit(ChronoUnit.DAYS.between(startDate, endDate) + 1);
    }

    public List<LocalDate> toList() { //could also be built from the stream() method
        List<LocalDate> dates = new ArrayList<>();
        for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
            dates.add(d);
        }
        return dates;
    }

}

Either way, today while debugging I found out that this is not working at all, I was wondering how iterating over a week took so long. Just to find out that it was iterating same days multiple times in random order.

Problem is probably me not understanding how to use this...

    for (LocalDate date : new DateRange(thymeDate.getDate_a(), thymeDate.getDate_b())) {

        List<Group_C> owners = getAllByDate(date);
        groupList = composeGroup.composeGroupForRange(groupList, owners);

    }
    return GroupList;
}

I've also tried DateRange.between() as in the example, which is not a function, so can't be used? and creating the new normal instance.

DateRange range = new DateRange(dateA, dateB)

and @Autowireing DateRange class.

How would I iterate over given days?

timeline in SysOut


Solution

  • This was ultimately a problem with double POST,caused by using proxy. DateRange method was fine all along... You can see solution for double POST problem in another thread Here

    Thanks to Ole V.V. for trying to help :)