Issue
I know, there are many examples how to remove something from a list while iterating over it, but thats not the point.
I'm trying to automatize a process that I need to document my work (in the end it should be printing into a document something like that 01.01.2019 - Tuesday). For that I have a UI with two datepicker. After selecting two different dates and comparing them I know how many days are between these dates.
Now the following problem:
I'm adding all days between the two dates in a list. After that I'm trying to block some specific days (always the same days: Monday, Saturday and Sunday). These are days that shouldn't be in the list anymore.
I tried things like removing the value out of the list while I'm iterating over it. But it doesn't work the way I expect it to.
Example:
I'm selecting the 17.09.2019 as beginning and 24.09.2019 as end. The expected output should be:
Weekday: TUESDAY
Date: 2019-09-18
Weekday: WEDNESDAY
Date: 2019-09-19
Weekday: THURSDAY
Date: 2019-09-20
Weekday: FRIDAY
Date: 2019-09-24
Weekday: TUESDAY
but if I run my code the output is:
Weekday: TUESDAY
Date: 2019-09-18
Weekday: WEDNESDAY
Date: 2019-09-19
Weekday: THURSDAY
Date: 2019-09-20
Weekday: FRIDAY
Date: 2019-09-21
Weekday: FRIDAY
Date: 2019-09-22
Weekday: FRIDAY
Date: 2019-09-23
Weekday: FRIDAY
Date: 2019-09-24
Weekday: TUESDAY
You can see it. The word Saturday, Sunday and Monday will get removed but it's still in the list.
Code:
long daysBetween = ChronoUnit.DAYS.between(dateBeginPicker.getValue(), dateEndPicker.getValue());
int db = Math.toIntExact(daysBetween);
String day = "";
List<LocalDate> dateList = new ArrayList<>();
LocalDate dateAfter = null;
for (int i = 0; i <= db; i++) {
dateAfter = dateBeginPicker.getValue().plusDays(i);
dateList.add(dateAfter);
}
for (Iterator<LocalDate> iterator = dateList.iterator(); iterator.hasNext();) {
LocalDate date = iterator.next();
if (date.getDayOfWeek().equals(DayOfWeek.SATURDAY) || date.getDayOfWeek().equals(DayOfWeek.SUNDAY) || date.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
iterator.remove();
dateList.remove(date);
}
else {
day = date.getDayOfWeek().toString();
}
System.out.println("Date: " + date);
System.out.println("Weekday: " + day);
}
What I expecting in the end is, that the every monday, saturday and sunday should removed out of the list, and the output should be correct (as in my example).
Thank you
Solution
You have your System.out.println() commands within the for-loop, but outside of the else-block. That's why all of the dates are displayed.
Just move those two lines inside the else-block and you will get the output you want.
Answered By - tehvan
Answer Checked By - Willingham (JavaFixing Volunteer)