OneXer
OneXer

Reputation: 355

Java iterate over map twice before deciding whether to remove an object

I have a map of Object string. I need to iterate over it twice before deciding whether to remove it or not.

protected void removeDayOutOfRangeObjects(Map<Object, String> objects, Calendar[] clientTimeRange) {
        String currentPartOfWeek = null;
        for(Calendar range: clientTimeRange){
            int dayOfWeek = range.get(Calendar.DAY_OF_WEEK); 
            if(1 == dayOfWeek || 7 == dayOfWeek) {
                currentPartOfWeek = "weekends";
            } else {
                currentPartOfWeek = "weekdays";
            }
            Iterator<Map.Entry<Object,String>> iter = objects.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<Object,String> entry = iter.next();

                if(currentPartOfWeek.matches(entry.getValue())){
                    continue;
                } else {
                    iter.remove();  // I need to remove the object only if true for both entries in the Calendar array  
                }
            }
        }
    }

Upvotes: 0

Views: 49

Answers (1)

Eran
Eran

Reputation: 393936

The obvious solution would be to reverse the order of the loops. Have the outer loop iterate over the Map entries, and the inner loop iterate over the array. In the inner loop, set some flag to true the first time your currentPartOfWeek.matches(entry.getValue()) is false (or true, it wasn't clear from your question when you want to remove the entry), and only remove that entry if that flag is true.

This way you only iterate once over the Map.

Basically, it will look like this:

Iterator<Map.Entry<Object,String>> iter = objects.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<Object,String> entry = iter.next();
    boolean remove = false;
    for(Calendar range: clientTimeRange) {
        if (someCondition) {
            if (remove) {
                iter.remove();
            } else {
                remove = true;
            }
        }
    }
}

Note that this relies on having two elements in your clientTimeRange array. If there are more elements, you should adjust the logic accordingly (i.e. decide when you want to remove the entry - after two elements of the array match the current Map entry? after all the elements of the array match the current entry?).

Upvotes: 1

Related Questions