/** * Java Collections Framework > HashMapExample.java * * Use a HashMap to store objects and retrieve them using keys. HashMaps * are faster than TreeMaps at retrieval but do not store their elements in * sorted order. * @author Feihong Hsu */ import java.util.Map; // Superclass of HashMap import java.util.HashMap; // A container that supports quick retrieval import java.util.Iterator; // Used to traverse the HashMap public class HashMapExample { // This method prints all the mappings in the given HashMap object. public static void printHashMap(HashMap hashMap) { System.out.print( "HashMap: " ); // Use an Iterator to traverse the mappings in the TreeMap. Iterator iterator = hashMap.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) { HashMap hashMap = new HashMap(); // Put 4 mappings into the HashMap. hashMap.put("Pharaoh", new Integer(55)); hashMap.put("Emperor", new Double(2.33)); hashMap.put("Kaiser", new Long(323322L)); hashMap.put("Czar", new Boolean(true)); // "HashMap: (Pharaoh: 55), (Czar: true), (Kaiser: 323322), // (Emperor: 2.33), " printHashMap(hashMap); // Get the value associate with the key "Emperor"--prints 2.33. System.out.println("Value for key Emperor: " + hashMap.get("Emperor") ); // Remove the hashMapping with key "Kaiser". hashMap.remove("Kaiser"); // "HashMap: (Pharaoh: 55), (Czar: true), (Emperor: 2.33), " printHashMap(hashMap); // Find out if the HashMap has the key "Sultan". System.out.println( "Has key Sultan? " + hashMap.containsKey("Sultan") ); // Prints false } } /* Output: HashMap: (Pharaoh: 55), (Czar: true), (Kaiser: 323322), (Emperor: 2.33), Value for key Emperor: 2.33 HashMap: (Pharaoh: 55), (Czar: true), (Emperor: 2.33), Has key Sultan? false */