Jorane Jorane - 1 month ago 6
Java Question

TreeMap with as its value a TreeSet, how to remove element from this TreeSet?

I have a TreeMap, where the values are TreeSet. Now I need to loop through the keys, and for each element of the TreeSet I have to delete that element (then continue to do something) and then delete the second element of that TreeSet etc.

I tried:

for (Integer w : adjacencyList.get(keyNow)){
adjacencyList.get(keyNow).remove(w);
}


this doesn't work, could somebody please help?

Answer

Use an explicit iterator :

if (adjacencyList.containsKey(keyNow)) {
    Iterator<Integer> iter = adjacencyList.get(keyNow).iterator();
    while (iter.hasNext()) {
        Integer w = iter.next();
        iter.remove();
    }
}
Comments