This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

First Key of HashMap

 
thippareddy mallikarjuna reddy
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi pals

How to find out first key from HashMap?

Thanks
Mallikarjuna
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By definition, there is no ordering of keys in a HashMap, so "first key" makes no sense.

If you are refering to LinkedHashMap, as mentioned in you previous post:

http://www.coderanch.com/t/380090/java/java/order-Map

just take the first key returned by the key set iterator:
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As the previous post states, the first key of a HashMap may not necesarily be the firt entry you put into the HashMap, since HashMap do not keep an specific order.

That being said, you can also obtain the first key in different ways. Another way to do it is:



I hope this helps!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64851
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thippareddy, please be sure to post questions in an appropriate forum. This is hardly an advanced question.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Edwin Dalorzo:
As the previous post states, the first key of a HashMap may not necesarily be the firt entry you put into the HashMap, since HashMap do not keep an specific order.

That being said, you can also obtain the first key in different ways. Another way to do it is:



I hope this helps!


If a HashMap makes no guarantee of the order of its elements, is this code guaranteed to return the same result every time ? The JavaDoc for Collection.toArray() says
If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

As a Set is not ordered I suspect the answer is 'No', but it would be good if someone could confirm this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic