• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How get haspmap in inserted order?

 
shyam sunder prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Rajesh Nagaraju
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My apologies, I got it all mixed up

Thanks Jesper
 
shyam sunder prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thankyou jasper,


can you explain it.
 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The enhanced for statement
The for Statement Tutorial
 
shyam sunder prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my condition is you should not use LinkedHashMap ok.

i want method to retrieve in order as i inserted.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic