Reputation: 43
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?
Upvotes: 2
Views: 220
Reputation: 533550
Similar to @Eran's answer but I would write it like this.
Set<Integer> ints = adjacencyList.get(keyNow);
if (ints != null) {
for (Iterator<Integer> iter = ints.iterator(); iter.hasNext();) {
Integer w = iter.next();
// do something with w
iter.remove();
}
}
Note: if you don't need to examine each value you can just clear the set.
Set<Integer> ints = adjacencyList.get(keyNow);
if (ints != null)
ints.clear(); // remove all.
Upvotes: 1
Reputation: 393856
Use an explicit iterator :
if (adjacencyList.containsKey(keyNow)) {
Iterator<Integer> iter = adjacencyList.get(keyNow).iterator();
while (iter.hasNext()) {
Integer w = iter.next();
iter.remove();
}
}
Upvotes: 3