2.3:map interface
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Create a Map of key-value pairs using HashMap
Map<String, Integer> myMap = new HashMap<>();
// Add key-value pairs to the map
myMap.put("Alice", 25);
myMap.put("Bob", 30);
myMap.put("Charlie", 35);
myMap.put("David", 40);
// Add a duplicate key (it will update the existing value)
myMap.put("Bob", 32);
// Access values by key
int ageOfAlice = myMap.get("Alice");
System.out.println("Age of Alice: " + ageOfAlice); // Output: Age of Alice: 25
// Iterate through the map and print key-value pairs
System.out.println("Map entries:");
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Check if a key exists in the map
boolean containsKeyCharlie = myMap.containsKey("Charlie");
System.out.println("Contains key 'Charlie'? " + containsKeyCharlie); // Output: Contains key 'Charlie'? true
// Get the size of the map
int size = myMap.size();
System.out.println("Map size: " + size); // Output: Map size: 4
// Remove a key-value pair from the map
myMap.remove("David");
// Check if the map is empty
boolean isEmpty = myMap.isEmpty();
System.out.println("Is the map empty? " + isEmpty); // Output: Is the map empty? false
}
}
No comments