iterating over elements of a HashMap

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
DJ_AM_JuiceboxAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
ksivananthConnect With a Mentor Commented:

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() ;
}

0
 
Ajay-SinghConnect With a Mentor Commented:

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

Open in new window

0
 
DJ_AM_JuiceboxAuthor 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
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
ksivananthCommented:
hashmap don't maintain the order, try using tree map!
0
 
ksivananthCommented:
sorry looks like, that will keep in a sorting order!
0
 
cmalakarCommented:
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
0
 
ksivananthCommented:
try use LinkedHashMap!
0
 
DJ_AM_JuiceboxAuthor 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
0
 
cmalakarConnect With a Mentor Commented:
Yes...
Just replace new HashMap()

With LinkedHashMap()

0
 
cmalakarCommented:
LinkedHashMap class is inherited from HashMap class
0
All Courses

From novice to tech pro — start learning today.