File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Sorting MAP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting MAP" Watch "Sorting MAP" New topic

Sorting MAP

Waez Ali
Ranch Hand

Joined: Jan 24, 2005
Posts: 43
Hi All,

I am reading some data from properties file, & want sort this based on keys and in some cases based on values.


1 = Hi
2 = hello
3 = Bye
4 = Thank You
5 = Thank You
6 = Bye

When I load the above data into my properties object data is n more sorted.

Can someone please help me out to sort this data after reading it from properties file ?

Thanks in advance.
Waez Ali.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Sounds like you want a java.util.TreeMap
Check the API
Dariusz Kordonski
Ranch Hand

Joined: Jul 11, 2008
Posts: 49
TreeMap will sort the properties according to natural ordering of keys (unless you explicitly specify your own Comparator). If you want to have your properties in the order, in which they exist in file, I guess you would have to use Scanner class.
Dariusz Kordonski
Ranch Hand

Joined: Jul 11, 2008
Posts: 49
I saw on the other post that you would like to sort properties by values without losing duplicate values. I don't know of any built-in API that could be used to accomplish this directly. You may use a kind of helper class, check out the example code:

But maybe there is an easier solution...
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15084

TreeMap keeps the entries of the map in the natural order of the keys (or in the order specified by a custom comparator) as already mentioned above.

If you want to keep the entries in the map in the order that they were added to the map, use LinkedHashMap (look it up in the API documentation for more info).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Sorting MAP
It's not a secret anymore!