import java.util.Iterator; import java.util.LinkedHashMap; public class HashMaps { // There are three types of HashMaps: HashMap, LinkedHashMap, TreeMap // Each HashMap entry contains a KEY and an associated VALUE // HashMap: Does NOT maintain the order in which elements are initially entered // LinkedHashMap: DOES maintain the order in which data is entered // TreeMap: Allow the map elements to be sorted by their keys // HashMaps store data in "buckets", which contain key/value pairs; a single // bucket can hold multiple key/value pairs (often organized via a List) // Hashing refers to the process of retrieving the Value for a specific Key private static LinkedHashMap mapData = new LinkedHashMap(); public static void main(String[] args) { // Inserting data into the HashMap mapData.put(37, "computer"); mapData.put(22, "monitor"); mapData.put(81, "keyboard"); mapData.put(74, "mouse"); mapData.put(6, "flash drive"); // Retrieve/Display an individual HashMap Value; note that to find the Key // associated with a specific Value requires iterating through the HashMap System.out.println("Value associated with Key 22: " + mapData.get(22)); // Retrieve/Display all of the HashMap data ShowMapData(); // Deleting data from the HashMap System.out.println("\nRemoving Values for Keys 81 and 37."); mapData.remove(81); mapData.remove(37); // Retrieve/Display all of the HashMap data ShowMapData(); // Display HashMap data System.out.println("\nDoes HashMap contain KEY 74? " + mapData.containsKey(74)); System.out.println("Does HashMap contain VALUE 'monitor'? " + mapData.containsValue("monitor")); System.out.println("\nSize of HashMap: " + mapData.size()); System.out.println("Is HashMap Empty? " + mapData.isEmpty()); // Change HashMap Data (could also use ".put") System.out.println("\nChanging the Value for Key 74."); mapData.replace(74, "speaker"); ShowMapData(); // Clear the HashMap System.out.println("\nClearing the HashMap."); mapData.clear(); System.out.println("\nSize of HashMap: " + mapData.size()); System.out.println("Is HashMap Empty? " + mapData.isEmpty()); } public static void ShowMapData() { // Retrieve/Display all of the HashMap data System.out.println("\nComplete Map Data:"); System.out.println(" All Keys: " + mapData.keySet()); System.out.println(" All Values: " + mapData.values()); System.out.println("\n Via Iteration:"); Iterator itr = mapData.keySet().iterator(); while (itr.hasNext()) { Integer key = (Integer)itr.next(); System.out.println(" " + key + ": " + mapData.get(key)); } } }