Map Interface
A basic Map
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println(ages.get("Alice"));
System.out.println(ages);30
{Alice=30, Bob=25}java.util package and is considered part of the broader Collections Framework — it's just not a Collection in the strict interface sense.Keys Must Be Unique
Putting a duplicate key overwrites the value
import java.util.HashMap;
import java.util.Map;
Map<String, String> capitals = new HashMap<>();
capitals.put("Japan", "Tokyo");
capitals.put("Japan", "Kyoto"); // overwrites the previous mapping
System.out.println(capitals.get("Japan"));
System.out.println(capitals.size());Kyoto 1
Common Map Methods
Method | Purpose |
put(key, value) | Adds a mapping, or overwrites the value if the key already exists |
get(key) | Returns the value for a key, or null if the key isn't present |
remove(key) | Removes the mapping for a key, if it exists |
containsKey(key) | Returns true if the map has a mapping for this key |
containsValue(value) | Returns true if any key maps to this value (O(n) scan) |
keySet() | Returns a Set view of all the keys |
values() | Returns a Collection view of all the values |
entrySet() | Returns a Set view of all the key-value pairs |
Using the core Map methods
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> stock = new HashMap<>();
stock.put("apples", 50);
stock.put("bananas", 30);
stock.put("cherries", 0);
System.out.println(stock.containsKey("bananas"));
System.out.println(stock.containsValue(0));
System.out.println(stock.keySet());
System.out.println(stock.values());
stock.remove("cherries");
System.out.println(stock);true
true
[apples, bananas, cherries]
[50, 30, 0]
{apples=50, bananas=30}Iterating a Map with entrySet()
Iterating with entrySet()
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> inventory = new HashMap<>();
inventory.put("widgets", 12);
inventory.put("gadgets", 7);
inventory.put("gizmos", 21);
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}widgets -> 12 gadgets -> 7 gizmos -> 21
Map.forEach() with a lambda
inventory.forEach((name, count) ->
System.out.println(name + " -> " + count));Map stores key-value pairs, not standalone elements
Map deliberately does not extend Collection
Keys are unique; put() with an existing key overwrites the value
entrySet() is the idiomatic way to iterate both keys and values together