We help IT Professionals succeed at work.

iterating over elements of a HashMap

DJ_AM_Juicebox
on
Hi,

I made a HashMap<String, Integer>. I want to iterator over all elements.

for (Iterator it = m_Table.values().iterator(); it.hasNext();) {
    Map.Entry entry = (Map.Entry)it.next();
    String strKey = (String)entry.getKey()
    Integer nData = (Integer)entry.getValue() ;
}

This causes a runtime exception though... what's the right way to do it?

Thanks
Comment
Watch Question


try this

for (Iterator it = m_Table.entrySet().iterator(); it.hasNext();) {
    Map.Entry entry = (Map.Entry)it.next();
    String strKey = (String)entry.getKey()
    Integer nData = (Integer)entry.getValue() ;
}


for(Map.Entry<String,Integer> entry: m_Table.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();
}

Open in new window

Author

Commented:
Hmm they work. But I don't get the order in which the keys are extracted. In my HashMap, I have keys:

"xy"
"z"

That was the order in which they were entered into the map too. But when I iterate over them, they come out in:

"z"
"xy"

order?

Thanks
hashmap don't maintain the order, try using tree map!
sorry looks like, that will keep in a sorting order!

Commented:
HashMap will not return the entries in order in which they were inserted..

If you want the same order in which you inserted, then you have to use.. LinkedHashMap
try use LinkedHashMap!

Author

Commented:
Ok I wrote my whole app (which is not that big really) using HashMap. The only operations I used from HashMap were get() and put().

So by switching the LinkedHashMap, I shouldn't have to change any of my use calls, right? The only difference is that now when I iterate over the elements, they'll come out in the order inserted?

Thanks
Commented:
Yes...
Just replace new HashMap()

With LinkedHashMap()

Commented:
LinkedHashMap class is inherited from HashMap class

Explore More ContentExplore courses, solutions, and other research materials related to this topic.