Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Map.get(key) lookup

 
Archana Honnavalli
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic