Java Docs
Java Documentation
Java Map Interface
The Map interface of the Java collections framework provides functionality for key/value pair data structures. Keys are unique, and each key is associated with a single value. A map cannot contain duplicate keys.
Classes Implementing Map
- HashMap
- EnumMap
- LinkedHashMap
- WeakHashMap
- TreeMap
Interfaces Extending Map
- SortedMap
- NavigableMap
- ConcurrentMap
Creating a Map
import java.util.Map; import java.util.HashMap; // Creating a Map using HashMap Map<String, Integer> numbers = new HashMap<>();
Common Map Methods
put(K, V)- Insert key/value pairputAll()- Insert all entries from another mapputIfAbsent(K, V)- Insert only if key is absentget(K)- Get value by keygetOrDefault(K, defaultValue)- Get value or defaultcontainsKey(K)/containsValue(V)replace(K, V)/replace(K, oldV, newV)remove(K)/remove(K, V)keySet(),values(),entrySet()
Example 1: Using HashMap
import java.util.Map;
import java.util.HashMap;
class Main {
public static void main(String[] args) {
Map<String, Integer> numbers = new HashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);
System.out.println("Keys: " + numbers.keySet());
System.out.println("Values: " + numbers.values());
System.out.println("Entries: " + numbers.entrySet());
int removedValue = numbers.remove("Two");
System.out.println("Removed Value: " + removedValue);
}
}Output: {One=1, Two=2}
Example 2: Using TreeMap
import java.util.Map;
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
Map<String, Integer> values = new TreeMap<>();
values.put("Second", 2);
values.put("First", 1);
System.out.println("Map using TreeMap: " + values);
values.replace("First", 11);
values.replace("Second", 22);
System.out.println("New Map: " + values);
int removedValue = values.remove("First");
System.out.println("Removed Value: " + removedValue);
}
}Output: {First=1, Second=2} → After replace: {First=11, Second=22} → Removed Value: 11