Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need help in properties file- key value pair

 
lokesh jain
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am a newbie in properties files. I am using a property file in which we have key-value pairs. I need to extract the keys in ascending order, however when I use this code
then it gives me the result in descending order, can you please help me getting the keys in ascending order.

Thanks in advance,
Lokesh
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Properties is a subclass of Hashtable<Object,Object> (why Object is used beats me, but ok), so the order is based on hash code, not the real order from the file.

Now, if you need alphabetical order, copy the contents to a TreeSet<String,String>. If you need the order from the properties file, you will need to do custom reading, probably using a LinkedHashMap<String,String>.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Properties are a kind of Map (which don't support ordering).

You could subclass the Properties class and add "keyList()" and/or "entryList()" methods to it (which would return an ordered List of what keySet and entrySet would return).

Alternatively, create a SortedMap of the Properties object like "SortedMap sm = new TreeMap(prop)" and iterate over that using entrySet or keySet.

(Edit: too late, I see...)
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob:

I think it was for backwards compatibility.

John.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably so, but a Properties object was never meant to store anything other than String keys and String values. The only reason it was possible to store anything is because Sun decided to make Properties extend Hashtable (it shouldn't have, really).

Sun have made a few more questionable choices like that, like Stack extending Vector.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob:

I agree. IMHO it would make much more sense just to wrap a HashMap<String, String> object, and add the necessary file and XML functionality.

John.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic