Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Ok to delete element from HashMap while iterating?

Posted on 2009-07-13
3
Medium Priority
?
657 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

610 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