Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

sorting the values using Hsh Map

 
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.
 
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 ]
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • 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.
 
(instanceof Sidekick)
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.
 
Wanderer
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 ]
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic