// Create a new HashMap object MapwordCount = new HashMap<>(); // Add some key-value pairs wordCount.put("apple", 3); wordCount.put("banana", 2); wordCount.put("orange", 5); // Retrieve the value for a specific key int count = wordCount.get("banana"); // Loop through all the keys and values for (Map.Entry entry : wordCount.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); }
// Create a new TreeMap object MapIn this example, we create a new TreeMap object and add some key-value pairs representing names and their corresponding numbers. We then remove a key-value pair from the map, check if a key is present, and loop through all the values in the map. This example uses the TreeMap class from the java.util package. Overall, the java.util Map provides a powerful and flexible way to store and retrieve key-value pairs in memory, with different implementations offering different features and performance characteristics.nameToNumber = new TreeMap<>(); // Add some key-value pairs nameToNumber.put(1, "Alice"); nameToNumber.put(2, "Bob"); nameToNumber.put(3, "Charlie"); // Remove a key-value pair nameToNumber.remove(2); // Check if a key is present in the map boolean containsKey = nameToNumber.containsKey(3); // Loop through all the values in the map for (String name : nameToNumber.values()) { System.out.println(name); }