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
Solved

Ok to delete element from HashMap while iterating?

Posted on 2009-07-13
3
629 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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
egit plugin on eclipse 8 82
throw exception 21 58
Detect Closed Loops (circles, figure-8s, etc) in PNG Images 6 56
add projects t working set in maven 2 22
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

856 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