Iterating over a map of labels and disposing them

156
June 30, 2019, at 11:40 PM

I wrote the following code:

final Iterator<Entry<Label, Label>> it = dataLabels.entrySet().iterator();
while (it.hasNext()) {
    final Map.Entry<Label, Label> pairs = it.next();
    dataLabels.remove(pairs.getKey());
    pairs.getValue().dispose();
    pairs.getKey().dispose();
}

It iterates over a map of labels (type: Map<Label, Label>) and dispose of each one of them (after removing it from the map).

I feel like this code does not do what I expect. I think that it stops iterating after the first loop (tried to add printed message to see the behavior).

Does the code do what I expect (disposing of all the labels)? If not, how to fix it?

Answer 1

If you want to remove one by one try this,

    Iterator<Map.Entry<Label,Label>> i = dataLabels.entrySet().iterator();
    while (i.hasNext()) {
       Map.Entry<String,String> entry = i.next();
       // Do something
       i.remove();
    }

or else you can clear entire map using dataLabels.clear()

By using dataLabels.clear() you can reuse the dataLabels map.

If you don't need to reuse it set it to null

dataLabels = null;
Answer 2

You can't call remove on a map while you are iterating through the entries.

You can either use the iterator remove method as shown in the other answer or just clear the map at the end:

for (Map.Entry<Label, Label> dataLabel : dataLabels.entrySet()) {
  dataLabel.getKey().dispose();
  dataLabel.getValue().dispose();
}
dataLabels.clear();

or using streams:

dataLabels.forEach((key, value) -> { key.dispose(); value.dispose(); });
dataLabels.clear();
Rent Charter Buses Company
READ ALSO
Unable to delete data from MS Access using GUI Java

Unable to delete data from MS Access using GUI Java

I am unable to delete a row from my databaseI included a photo with the table & the code

130
How to import .cer / .p12 into mobile application

How to import .cer / .p12 into mobile application

I have a SOAP request to make through HTTPS which requires a self-signed certificateI have it in the format of

201
Negative lookbehind: How can I stop matches when the suffix is repeated?

Negative lookbehind: How can I stop matches when the suffix is repeated?

I have some suffix that I want to match when some prefix is absentHowever, the suffix might be repeated

141
Installing AppDynamics with Java/Tomcat

Installing AppDynamics with Java/Tomcat

I am currently installing AppDynamics agent to monitor a Java App

163