I have the following TreeMap:
private Map<Date,WeekSchedule> weeks = new TreeMap<Date,WeekSchedule>();
And I need to remove all entries, whose date is before a given value.
What is the most efficient way to do this?
This is what I have so far:
public void removeWeeksBefore(Date monDate){
for (Map.Entry<Date, WeekSchedule> entry : weeks.entrySet()){
if(entry.getKey().before(monDate)){
weeks.remove(entry.getKey()); //This will destroy the iterator
}else{
return;
}
}
}
The most efficient way is probably storing this as a SortedMap
and then using the one line
map.headMap(monDate).clear();
Since you don't care about the map values, you only need to iterate over the keySet
:
Iterator<Date> iter = weeks.keySet().iterator();
while (iter.hasNext()) {
if (iter.next().before(monDate))
iter.remove();
else
return; // since TreeMap is sorted by key
}
You can use the iterator instead of for-each loop, if you are modifying the Iterable
.
for (Iterator<Entry<Date, WeekSchedule>> i = weeks.entrySet().iterator() ; i.hasNext(); ){
Entry<Date, WeekSchedule> entry = i.next();
if(entry.getKey().before(monDate)){
i.remove();
}else{
return;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With