File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Map.get(key) lookup Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Map.get(key) lookup" Watch "Map.get(key) lookup" New topic
Author

Map.get(key) lookup

Archana Honnavalli
Ranch Hand

Joined: Feb 26, 2008
Posts: 39
Hi,
Can someone explain me.
Why using Map.get(key) is inefficient?
This will return the corresponding value of the HashMap.

Why is using entrySet efficient?
I understand Map.entrySet converts HashMap to an Iterator.
Then by giving the key we can fetch value from Iterator.


Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Archana Honnavalli wrote:Hi,
Can someone explain me.
Why using Map.get(key) is inefficient?


It's not. Why do you think it is?

Why is using entrySet efficient?


Oohhhhh, so you're talking about in the context of an iteration.

Getting a value during iteration using the getValue() of the Entry from entrySet() and getting it during an iteration using get() based on the key from keySet() are both O(1). However, Entry's getValue() method will probably have fewer steps to retrieve the value than get() will, particularly if there are a lot of collisions in your map.

I still wouldn't call get() inefficient though, and in most cases, you'll never notice any difference in the context of an application's performance.

I understand Map.entrySet converts HashMap to an Iterator.


No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.
Archana Honnavalli
Ranch Hand

Joined: Feb 26, 2008
Posts: 39

No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.


Right. My bad.
It provides an Iterator over Map's entries and we can extract value from Iterator by providing the key.
Correct?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Archana Honnavalli wrote:

No, it doesn't "convert" it. It just provides an Iterator over the Map's entries.


Right. My bad.
It provides an Iterator over Map's entries and we can extract value from Iterator by providing the key.
Correct?


"Extract the value from the Iterator by providing the key" isn't really accurate.

EntrySet provides an iterator over Set<Map.Entry>. Whether Map.Entry.getValue() provides "direct" access to the value or is just a wrapper around something like map.get(getKey()) is unspecified. So I guess I spoke too strongly when I said, "Entry's getValue() method will probably have fewer steps to retrieve the value". I should have say it may provide more direct access.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Map.get(key) lookup