In Java, the Map interface is part of the Java Collections Framework. A Map is used to store data in key–value pairs, where each key maps to exactly one value. Unlike lists, a Map does not store elements by index. Instead, it uses a key to retrieve the associated value.
Maps are very useful when we want to store and access data using a unique identifier.
Key Features of Map:
- Stores data as key-value pairs
- Keys are unique, but values can be duplicated
- Part of java.util package
- A single null value in the key is allowed, and multiple null values in the values are allowed
Since a Map is an interface, we cannot create its object directly. We must use a class that implements it..
Common Implementation of Map:
- HashMap
- LinkedHashMap
- TreeMap
What is HashMap:
- Does not maintain insertion order
- Allows one null key and multiple null values
- Store elements in hash table structure
HashMap<Integer,String> empMap= new HashMap<>();
What is LinkedHashMap:
- Maintain insertion order
- Slightly slower than HashMap
What is TreeMap:
- Stores elements in sorted order of keys
- Does not allow null keys
** Methods in Map (with examples)**
put(K key, V value)
-Inserts or updates a key-value pair.
Map<String, Integer> map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
get()
Retrieves the value associated with a key.
int age = map.get("Alice"); // 30
containsKey()
Checks if the map contains a specific key.
boolean exists = map.containsKey("Bob"); // true
remove()
Removes the mapping for a specific key.
map.remove("Bob")
Size()
Used to return the number of key/value pairs available in the map
map,size();
ContainsValue()
Cehcks if the map contains a specific values
map.containsValue(Value);//
map.containsValue(101);
isEmpty()
Checks whether the map is empty or not.
map.isEmpty();//false
clear()
Removes all entries from the map
map.clear()
keySet()
Returns a Set of all keys in the map.
Set<KeyType> keys = map.keySet();
values()
Returns a Collection of all values in the map.
Collection<ValueType> values = map.values();
entrySet()
Returns all key–value pairs as a Set of Map.Entry objects.
Set<Map.Entry<KeyType, ValueType>> entries = map.entrySet();
| Method | Purpose |
| ----------------- | --------------------- |
| `put()` | add key-value pair |
| `get()` | retrieve value |
| `remove()` | delete entry |
| `containsKey()` | check key |
| `containsValue()` | check value |
| `size()` | number of entries |
| `isEmpty()` | check if map is empty |
| `clear()` | remove all entries |
| `keySet()` | get all keys |
| `values()` | get all values |
| `entrySet()` | get key-value pairs |
Top comments (0)