how to avoid sorting a TreeMap
807580Apr 2 2010 — edited Apr 5 2010I would like to add items into a TreeMap, but I do not want to change the sort ordering. In other words, I want to preserve the ordering of these items as they were added into the list, as a first-in/first-out style of sort ordering (and do not sort them by "natural ordering" or anything else).
For example:
import java.util.TreeMap;
import java.util.Iterator;
// Add the data into the TreeMap.
TreeMap<String,Double> myComponents = new TreeMap<String,Double>();
myComponents.put("milk", new Double(5.25));
myComponents.put("eggs", new Double(1.23));
myComponents.put("sausage", new Double(3.14));
myComponents.put("ham", new Double(12.12));
myComponents.put("soda", new Double(0.75));
// Print the TreeMap's contents.
Iterator iterator = myComponents.keySet().iterator();
while (iterator.hasNext()) {
String myName = iterator.next().toString();
Double myCost = myComponents.get(myName);
System.out.println("myName=" + myName + ", myCost=" + myCost);
}
The actual output of the above code (with a "natural order" alphanumeric sort) is...
myName=eggs, myCost=1.23
myName=ham, myCost=12.12
myName=milk, myCost=5.25
myName=sausage, myCost=3.14
myName=soda, myCost=0.75
The desired output (to output the items using the original ordering) would be...
myName=milk, myCost=5.25
myName=eggs, myCost=1.23
myName=sausage, myCost=3.14
myName=ham, myCost=12.12
myName=soda, myCost=0.75
I do not need to use a TreeMap for this (in case other Java objects might be more useful), but I am using TreeMaps to enforce sort-ordering on other lists of data in this application, and it would be desirable to keep similar objects if possible.