Solved

Ok to delete element from HashMap while iterating?

Posted on 2009-07-13
3
615 Views
Last Modified: 2012-05-07
Hi,

Is it legal to remove an element from a HashMap while iterating over it? Something like:

  HashMap<Integer, String> test = new HashMap<Integer, String();
  test.put(0, "a");
  test.put(1, "b");
  test.put(2, "c");

  for(Entry<Integer, String> entry : test.entrySet()){
      if (entry.getValue().equals("b")) {
          test.remove(entry.getKey());
      }
      // Ok to keep iterating?
  }

Thanks
0
Comment
Question by:DJ_AM_Juicebox
  • 2
3 Comments
 
LVL 92

Expert Comment

by:objects
ID: 24846020
you can but you need to use an Iterator and its remove() method'
How you are doing it will not work
0
 

Author Comment

by:DJ_AM_Juicebox
ID: 24846051
Ok but what do you mean with an iterator and a remove method?

Thanks
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 24846063
Iterator i = test.keySet().iterator();
while (i.hasNext()) {
     Integer key = i.next();
     String value = test.get(key);
     if (value.equals("b")) {
        i.remove();
    }
}
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now