1

I am in the process of updating some old Java code I havent touched in a while and have a quick question about the following code snippet:

private Map<String, Example> examples = new ConcurrentHashMap<String, Example>();

...

public void testMethod() {
    Enumeration allExamples = examples.elements();
    while (allExamples.hasMoreElements()){
    //get the next example
    Example eg = (Example) allExamples.nextElement();
    eg.doSomething();

}

It had previously used a hashtable, but I have replaced that with a thread safe hash map. My question is, what is the best way to iterate through a hashmap? as Enumeration has been deprecated. Should I just use a for each loop?

Any advice would be greatly appreciated.

Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68

2 Answers2

4

yep use a for-each loop, for-each/enhanced loop was introduced for the purpose of iterating over a collection/arrays. But you can only iterate over a collection using for-each if and only if your collection implements Iterable interface.

for(Map.Entry<String, Example> en: example.entrySet()){
System.out.println(en.getKey() + "  " + en.getValue());
}
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

Since you only process the values:

public void testMethod() 
{
    for (Example ex : allExamples.values())
    {
        ex.doSomething();
    }
}
Robin
  • 24,062
  • 5
  • 49
  • 58