• Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting the values using Hsh Map  RSS feed

 
Raja Sekhar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I need to sort the names and corresponding the values are sorted to it and need to be displayed ,
can anyone suggest the required method.
 
satyabrat mishra
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Map<String, object> set = new TreeMap<String, object>();
put names as key and values as value.
it will automatically sort the names and values.
[ October 29, 2007: Message edited by: satyabrat mishra ]
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A HashMap is not a sorted collection, so you cannot sort items while they are in a HashMap.

A TreeMap sorts its elements by key.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need to retrieve values by key and iterate them in sequence, you may have to use two collections. You can get the values as a set and make a TreeSet. That will not only sort them, but will also remove duplicates, which may or may not be a good thing.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be clear, Jesper is talking about sorting by the key, and Stan is apparently talking about sorting by value. It's not immediately clear which is desired here, although I think sorting by key is more common. If you want to sort values without eliminating duplicates, don't put them in a Set - just use toArray() and then use Arrays.sort().
[ October 29, 2007: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!