Search code examples
javatreemap

How to delete entry in Java TreeMap?


I am making a method, which takes a provided TreeMap, removes entries where the key is a multiple of keyFilter and the value contains the valueFilter character, and then returns the resulting TreeMap.

This is what I have so far:

public static TreeMap<Integer, String> filterTreeMap(
        TreeMap<Integer, String> map, int keyFilter, char valueFilter) {
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
        int mapKey = entry.getKey();
        String mapValue = entry.getValue();
        if (mapKey%keyFilter == 0 && mapValue.indexOf(valueFilter) != -1) {
            map.remove(mapKey);
        }
    }
    return map;
}

However, under the if condition where I want to delete the entries, I don't know how to delete entries in tree map. As far as I know, there is no existing method that I can use?


Solution

  • Use an Iterator. As the Iterator.remove() Javadoc notes

    The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

    Something like

    public static TreeMap<Integer, String> filterTreeMap(TreeMap<Integer, String> map,
            int keyFilter, char valueFilter) {
        Iterator<Map.Entry<Integer, String>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Integer, String> entry = iter.next();
            int mapKey = entry.getKey();
            String mapValue = entry.getValue();
            if (mapKey % keyFilter == 0 && mapValue.indexOf(valueFilter) != -1) {
                iter.remove();
            }
        }
        return map;
    }