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.
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>.
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.
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
Joined: Mar 09, 2009
Posts: 600
posted
0
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.