Junior
Tell about the Map collection in Java and its features.
sobes.tech AI
Answer from AI
Map is an interface in the Java Collection Framework that represents a collection of key-value pairs. Keys are unique, while values can be duplicated.
Main features:
- A key is used to access the corresponding value.
- The same key cannot be added twice. When attempting to add an existing key, the old value is replaced with the new one.
Mapdoes not inherit from theCollectioninterface. It has its own methods for working with "key-value" pairs.- The order of key-value pairs may vary depending on the specific implementation.
Popular implementations of Map:
HashMap: Does not guarantee the order of elements. Provides high performance for most operations (insertion, retrieval, deletion) in the absence of hash conflicts.LinkedHashMap: Stores elements in the order they were added (or in access order if configured accordingly).TreeMap: Stores elements in a sorted order by key (natural order or provided comparator). Ensures logarithmic time for most operations.
Examples of methods:
// Get value by key
Object value = map.get(key);
// Add or update a key-value pair
Object oldValue = map.put(key, value);
// Remove a pair by key
Object removedValue = map.remove(key);
// Check if key exists
boolean containsKey = map.containsKey(key);
// Check if value exists
boolean containsValue = map.containsValue(value);
// Get all keys
Set<KeyType> keys = map.keySet();
// Get all values
Collection<ValueType> values = map.values();
// Get all entries (key-value pairs)
Set<Map.Entry<KeyType, ValueType>> entries = map.entrySet();
// Get size of the Map
int size = map.size();
Using Map.Entry during iteration:
// Iterate over Entry set
for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
KeyType key = entry.getKey();
ValueType value = entry.getValue();
// ...
}