Iterating over two lists and removing a value on condition in Kotlin
there are several problems in the code.
At the line val newAvailableList: MutableList<String> = listOfAvailableSlots
you are not initializing a new list containing the values of listOfAvailableSlots
. You are assigning the pointer of listOfAvailableSlots
to newAvailableList
so every action you perform on newAvailableList
is reflected to listOfAvailableSlots
. The easiest way to copy a list to another variable is using .toMutableList(). It works even if the source list is already mutable. val newAvailableList: MutableList<String> = listOfAvailableSlots.toMutableList()
The code below can be modified
for (j in 0 until listOfAvailableSlots.size) {
val hour = listOfAvailableSlots[j]
val endTime = createTime(hour)
if (endTimeOfAppointment.compareTo(endTime) >= 0) {
newAvailableList.removeAt(j)
}
}
to this
for(availableSlot in listOfAvailableSlot) {
val endTime = createTime(availableSlot)
if(endTimeOfAppointment.compareTo(endTime) >= 0) { //consider to use greaterThan or lessThan
newAvailableList.remove(availableSlot)
}
}
which is safer than the previous.
In the same way you can use the filter function:
newAvailableList.filter { endTimeOfAppointment.compareTo(createTime(it) >= 0) }
Try to clean your code and let us know if you solved the problem