aspose file tools*
The moose likes Java in General and the fly likes How get haspmap in inserted order? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How get haspmap in inserted order?" Watch "How get haspmap in inserted order?" New topic
Author

How get haspmap in inserted order?

shyam sunder prasad
Ranch Hand

Joined: Mar 23, 2011
Posts: 62
hi every one,

i am proud to say to be part of code ranch because when i pass question i am getting positive responses.




if i want to retrieve the values from hashmap ,it may not follow order as i inserted.for that i need to go for

so,in my interview he asked me that as any predefined method is there to retrieve the data from hashmap as we inserted?
please give me solution.
Rajesh Nagaraju
Ranch Hand

Joined: Nov 27, 2003
Posts: 61
There is nothing in a hashMap you can use to get it in the inserted order, however you can use a Tree Map. Tree Map retrieves values in the inserted order
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14150
    
  18

Rajesh Nagaraju wrote:Tree Map retrieves values in the inserted order

No, it doesn't. TreeMap sorts the elements by the "natural" order of the keys.

LinkedHashMap will return the elements in the order they were inserted into the map when you iterate over the keySet(), entrySet() or values() of the map.


This will print the elements in the order they were put into the map:

id = 3
name = shyam
age = 26


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rajesh Nagaraju
Ranch Hand

Joined: Nov 27, 2003
Posts: 61
My apologies, I got it all mixed up

Thanks Jesper
shyam sunder prasad
Ranch Hand

Joined: Mar 23, 2011
Posts: 62
thankyou jasper,


can you explain it.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4543
    
    5

The enhanced for statement
The for Statement Tutorial


luck, db
There are no new questions, but there may be new answers.
shyam sunder prasad
Ranch Hand

Joined: Mar 23, 2011
Posts: 62
my condition is you should not use LinkedHashMap ok.

i want method to retrieve in order as i inserted.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

shyam sunder prasad wrote:my condition is you should not use LinkedHashMap ok.

i want method to retrieve in order as i inserted.


Then that's exactly what a LinkedHashMap does, as has been pointed out. Why don't you want to use that?

In a plain HashMap, the information simply doesn't exist any more once they've been added. So your only options would be to extend and modify HashMap (in other words, write your own LinkedHashMap), or keep a separate list of the items you've added so you can control the order of iteration.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How get haspmap in inserted order?