Solved

Ok to delete element from HashMap while iterating?

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Problem to start Neon 20 83
thymeleaf natural templating vs JSP 2 65
Spring Framework HTTPSession management 1 21
arguments to jar 5 7
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to implement Singleton Design Pattern in Java.

932 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

9 Experts available now in Live!

Get 1:1 Help Now