import java.util.HashMap; import java.util.Map; public class HashMapMethodsExample { public static void main(String[] args) { // Creating a HashMap to store names and ages HashMap<String, Integer> ageMap = new HashMap<>(); // Adding key-value pairs to the HashMap ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); // Accessing values using get() method System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); // Updating a value using put() method ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); // Checking if a key exists String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } // Removing an entry using remove() method ageMap.remove("Alice"); System.out.println("Map after removing Alice: " + ageMap); // Iterating over map entries System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } // Checking size and emptiness System.out.println("Size of map: " + ageMap.size()); System.out.println("Is map empty? " + ageMap.isEmpty()); // Checking if map contains a key and value System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob")); System.out.println("Contains value 35: " + ageMap.containsValue(35)); // Clear the map ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter