I wrote the following code:
I have a text file which contains key value pairs. A=1, Z=2, K=3, L=4. When i execute the above code, the order of entry in the text file is different from the output that is printed. I have to maintain the same order as in the text file. I don't need alphabetical order since i can accomplish it using Tree related APIs and the key value pairs can also repeat so neither can i use Set APIs.
Please provide me a solution for maintaining the order of entries of key value pairs in the text file in the output printed.
Thank you very much,
Vijay Chandran wrote:key value pairs can also repeat
If you have repeating keys then that throws Map right out. I would wrap the key/value pair as my own object type and then throw that object into a LinkedList, but that's just me. If your values repeat but not your keys then the LinkedHashMap should have solved your problem.
Take a close look at this sentence from the JavaDocs about LinkedHashMap "Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)" You may be reinserting duplicate keys and expecting something different than it's designed to do. GL
Vijay Chandran wrote:Order of the elements should be maintained because i have to create XML tags based on the key value pairs. The XML is checked against a DTD, so the order of the elements is a priority.
Like i mentioned before "Properties is backed by HashTable" , so the attempt to get keys will not return in right order. and use of LinkedhashMap is pointless.
If you want to maintain order to prepare XML and dont mind where the keys fetched from. Then go for "|" and "$" combination of normal flat file and split Strings to StringTokenizer with "|" delimiter.
eg : A$1|B$2|L$4
Use StringTokenizer "|" as delimiter , this will fetch you "A$1" , again use "$" delimiter to get key and values in order and store in LinkedHashMap.
If you are required to run in the order of the DTD consider working in the opposite direction:
1) Iterate over the order in the DTD in a linear fashion (maybe a SAX Parser will help? Not sure)
2) For each element in the DTD - Get the property from the properties file and generate the XML
So then you are both maintaining the order required by the DTD and more-or-less validating your output to the DTD at the time of XML creation. And you don't have to worry about read-order of the properties file.