/** * Java Collections Framework > TreeMapExample.java * * Use a TreeMap to store and retrieve objects using keys. TreeMaps are * slower than HashMaps at retrieval but store their elements in sorted * order. Note that for ordering to be meaningful, all keys in a TreeMap * must be mutually comparable. * @author Feihong Hsu */ import java.util.Map; // Superclass of TreeMap import java.util.TreeMap; // A container that supports lookup of values // using keys import java.util.Iterator; // Used to traverse the TreeMap public class TreeMapExample { // This method prints all the mappings in the given TreeMap object. public static void printTreeMap(TreeMap treeMap) { System.out.print( "TreeMap: " ); // Use an Iterator to traverse the mappings in the TreeMap. Note // that the mappings are in sorted order (with respect to the keys). Iterator iterator = treeMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); System.out.print( "(" + entry.getKey() + ": " + entry.getValue() + "), " ); } System.out.println(); } public static void main(String[] args) { TreeMap treeMap = new TreeMap(); // Put 4 mappings into the TreeMap. treeMap.put("Pharaoh", new Integer(55)); treeMap.put("Emperor", new Double(2.33)); treeMap.put("Kaiser", new Long(323322L)); treeMap.put("Czar", new Boolean(true)); // "TreeMap: (Czar: true), (Emperor: 2.33), (Kaiser: 323322), // (Pharaoh: 55), " printTreeMap(treeMap); // Get the value associate with the key "Emperor"--prints 2.33. System.out.println("Value for key Emperor: " + treeMap.get("Emperor") ); // Remove the mapping with key "Kaiser". treeMap.remove("Kaiser"); // TreeMap: (Czar: true), (Emperor: 2.33), (Pharaoh: 55), printTreeMap(treeMap); // Find out if the TreeMap has the key "Sultan". System.out.println( "Has key Sultan? " + treeMap.containsKey("Sultan") ); // Prints false } } /* Output: TreeMap: (Czar: true), (Emperor: 2.33), (Kaiser: 323322), (Pharaoh: 55), Value for key Emperor: 2.33 TreeMap: (Czar: true), (Emperor: 2.33), (Pharaoh: 55), Has key Sultan? false */