wood burning stoves 2.0*
The moose likes Java in General and the fly likes First Key of HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "First Key of HashMap" Watch "First Key of HashMap" New topic
Author

First Key of HashMap

thippareddy mallikarjuna reddy
Greenhorn

Joined: Mar 08, 2006
Posts: 19
Hi pals

How to find out first key from HashMap?

Thanks
Mallikarjuna
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
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:


There is no emoticon for what I am feeling!
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
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

Joined: Jan 10, 2002
Posts: 61457
    
  67

thippareddy, please be sure to post questions in an appropriate forum. This is hardly an advanced question.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3720
    
  16
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.


Joanne
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: First Key of HashMap