Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get values from Hash Map in optimised way

 
Shashi Kala
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

I stored some information in HashMap and getting back that information as shown below. See the following code.

---------------------------------------------------
HashMap mInfo = queryResponse.getInfo();
if(mInfo==null) mInfo = new HashMap();
Set set = mInfo.entrySet();
Iterator im = set.iterator();
while(im.hasNext())
{
Map.Entry me = (Map.Entry)im.next();
if(mId.equals((String)me.getKey()))
{
mName = (String)me.getValue();
break;
}
}
---------------------------------------------------
See as shown above, I got the information back. But is there any other way to do same but bit optimistic? Help me posting the answer back...!!


Best Regards
------------
Shashi Kala
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My goodness, friend, you seem not to have understood the point of Maps. The "get" method returns the value associated with a given key, if any; otherwise it returns null. So you can say, for example,

 
Shashi Kala
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ernest,

Yes!! null check I should do..But why I did not do so means, I know that, if any key value is equal to mid, there is a value too..because those values I put in Hash map previous..Any ways, But Its good to check for null condition. I will change it.

But, to get key is there any other way, instead of using getKey() method??

Regards,

Shashi Kala
 
Shashi Kala
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry! Ernest,

I misunderstood what you said. Now I got it. Thanks you very much.

Regards,

Shashi Kala
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note that a value can be null too. If you want to allow this if it was set, use containsKey as well:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic