Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove TreeMap entries less than x

Tags:

java

map

treemap

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;
        }
    }
}
like image 759
maja Avatar asked May 29 '14 15:05

maja


3 Answers

The most efficient way is probably storing this as a SortedMap and then using the one line

map.headMap(monDate).clear();
like image 148
Louis Wasserman Avatar answered Oct 13 '22 12:10

Louis Wasserman


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
}
like image 36
arshajii Avatar answered Oct 13 '22 10:10

arshajii


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;
        }
    }
like image 38
sanbhat Avatar answered Oct 13 '22 11:10

sanbhat