Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

First Key of HashMap  RSS feed

 
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
 
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:
 
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!
 
Author and ninkuma
Marshal
Posts: 66684
167
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.
 
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.
 
It would give a normal human mental abilities to rival mine. To think it is just a tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!