Java Map Interface
Java Map Interface
Interface
A map stores values based on keys, forming key-
value pairs. Each pair is an entry. Maps have unique
keys.
Java Map Hierarchy
Interfaces Classes
2 Duplicate Values
Duplicate values are permitted.
3 Nulls
HashMap and LinkedHashMap allow null keys and values.
4 TreeMap
TreeMap doesn't allow null keys or values.
Map Traversal
Maps cannot be directly traversed. Convert to Set
using keySet() or entrySet() methods.
Map Implementations
HashMap
Implements Map, no order maintained.
LinkedHashMap
Implements Map, maintains insertion order.
TreeMap
Implements Map and SortedMap, maintains
ascending order.
Map Interface Methods
Method Description
putIfAbsent(K key, V value) Inserts the specified value with the specified key only if it's not
already present.
remove(Object key, Object value) Removes the specified values with the associated specified keys.
Map Interface Methods (cont.)
Method Description
entrySet() Returns a Set view containing all the keys and values.
compute(K key, BiFunction remappingFunction) Computes a mapping for the specified key and its current
mapped value.
computeIfAbsent(K key, Function mappingFunction) Computes a value using the given mapping function if the key is
not associated with a value.
Map Interface Methods (cont.)
Method Description
get(Object key) Returns the object that contains the value associated with the key.
getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or
defaultValue if the map contains no mapping for the key.
merge(K key, V value, BiFunction remappingFunction) Associates the specified key with the given non-null value if the
key is not already associated with a value or is associated with
null.
Map Interface Methods (cont.)
Method Description