Curriculum
In Java, the Map interface is used to represent a collection of key-value pairs. Each key in a Map is unique, and the value associated with that key can be retrieved using the key. Here’s an explanation of the Map interface and some examples of how it can be used:
Map<String, Integer> map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30); map.put("Charlie", 35);
In this example, we’ve created a Map that associates names (strings) with ages (integers). We’ve added three entries to the Map using the put() method.
int aliceAge = map.get("Alice"); System.out.println("Alice's age is " + aliceAge);
In this example, we’ve retrieved the value associated with the key “Alice” and stored it in a variable called aliceAge. We’ve then printed out a message that displays Alice’s age.
map.remove("Bob");
In this example, we’ve removed the entry associated with the key “Bob” from the Map.
for (Map.Entry<String, Integer> entry : map.entrySet()) { String name = entry.getKey(); int age = entry.getValue(); System.out.println(name + " is " + age + " years old."); }
In this example, we’re iterating over the entries in the Map and printing out a message for each one that displays the name and age of the person. The entrySet() method returns a set of all the entries in the Map, and each entry contains both the key and the value. We’re using the getKey() and getValue() methods of the Entry interface to extract the key and value from each entry.