• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting HashMaps  RSS feed

 
chintu reddy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi... i want to list students on jsp page based on their names.. my query returns students Ordered on names. But when I am putting obtained results in HashMap, the records in HashMap are sorting automatically based on key(which is Student ID,).. i mean, if I put (1,john), (3, paul)(2, robert) sequentially, map sorts itself to (1,john)(2,robert)(3,paul)..

how to over come this problem.. Are their any other collections/Maps to achieve this? OR can I make HashMap not auto sorting - like if I put (1,john), (3, paul)(2, robert)
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maps don't sort by their keys, but by the keys' hash code % Map's size. In the case of Integer, the hash code and the value are the same. Have a look in the Java™ Tutorials in collections and look for "Map implementations"; there are probably Maps which can be sorted. If you don't find any of them, Google for Jakarta Commons.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To maintain insertion order use LinkedHashMap.
 
chintu reddy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Rob.. LinkedHashMap is exactly what I wanted
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!