Maps are a data structure that takes data in key and value pairs, each key and value pair is known as an entry. A Map contains unique keys, used to search, update or delete elements based on a key.
There are two interfaces for implementing Map in Java Map and SortedMap and three classes HashMap, LinkedHashMap, and TreeMap.
Use case demonstrating map
Output:
Methods available on the map
Method |
Description |
V put(Object key, Object value) |
It is used to insert an entry in the map. |
void putAll(Map map) |
It is used to insert the specified map in the map. |
V putIfAbsent(K key, V value) |
It inserts the specified value with the specified key in the map only if it is not already specified. |
V remove(Object key) |
It is used to delete an entry for the specified key. |
boolean remove(Object key, Object value) |
It removes the specified values with the associated specified keys from the map. |
Set keySet() |
It returns the Set view containing all the keys. |
Set> entrySet() |
It returns the Set view containing all the keys and values. |
void clear() |
It is used to reset the map. |
V compute(K key, BiFunction remappingFunction) |
It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
V computeIfAbsent(K key, Function mappingFunction) |
It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. |
V computeIfPresent(K key, BiFunction remappingFunction) |
It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. |
boolean containsValue(Object value) |
This method returns true if some value equal to the value exists within the map, else return false. |
boolean containsKey(Object key) |
This method returns true if some key equal to the key exists within the map, else return false. |
boolean equals(Object o) |
It is used to compare the specified Object with the Map. |
void forEach(BiConsumer action) |
It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V get(Object key) |
This method returns the object that contains the value associated with the key. |
V getOrDefault(Object key, V defaultValue) |
It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. |
int hashCode() |
It returns the hash code value for the Map |
boolean isEmpty() |
This method returns true if the map is empty; returns false if it contains at least one key. |
V merge(K key, V value, BiFunction remappingFunction) |
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
V replace(K key, V value) |
It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) |
It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction function) |
It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
Collection values() |
It returns a collection view of the values contained in the map. |
int size() |
This method returns the number of entries in the map. |
Hashmap is used to store key-value pairs, keys should be unique and it is not synchronized. Let us assume a hashmap like the below structure before getting into detail
Bucket 0 |
Bucket1 |
Bucket 2 |
Each bucket is assigned with the key and value. It is more like a Hashtable permitting null.
Hashmap has two parameters that affect its performance
- Initial capacity
- Load factor
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed which means the number of buckets is doubled
The default value of initial capacity is 16 and the load factor is 0.75.Constructor
Constructor
HashMap() Constructs an empty HashMap with the default initial capacity and the default load factor. HashMap(int initialCapacity) Constructs an empty HashMap with the specified initial capacity and the default load factor. HashMap(int initialCapacity, float loadFactor) Constructs an empty HashMap with the specified initial capacity and load factor. HashMap(MapK,? extends V> m) Constructs a new HashMap with the same mappings as the specified Map. |
Use case demonstrating hashmap
The below example demonstrates how to add,remove and display a hashmap
Output
Methods available
Method |
Description |
clear() |
Removes all of the mappings from this map. |
|
Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. |
entrySet() |
Returns a |
get(Object key) |
Returns the value to which the specified key is mapped, or |
isEmpty() |
Returns true if this map contains no key-value mappings. |
keySet() |
Returns a |
put(K key, V value) |
Associates the specified value with the specified key in this map. |
putAll |
Copies all of the mappings from the specified map to this map |
remove(Object key) |
Removes the mapping for the specified key from this map if present. |
replace(K key, V value) |
Replaces the entry for the specified key only if it is currently mapped to some value. |
size() |
Returns the number of key-value mappings in this map. |
values() |
Returns a |
Java LinkedHashMap class is a non-synchronized hashtable that maintains insertion order. It inherits the HashMap class and implements the Map interface.Java LinkedHashMap contains unique elements values based on the key which may have one null key and multiple null. The initial default capacity of the Java hashmap class is 16 with a load factor of 0.75.
Use case demonstrating LinkedHashMap
Methods available
Method |
Description |
V get(Object key) |
It returns the value to which the specified key is mapped. |
void clear() |
It removes all the key-value pairs from a map. |
boolean containsValue(Object value) |
It returns true if the map maps one or more keys to the specified value. |
Set> entrySet() |
It returns a Set view of the mappings contained in the map. |
void forEach(BiConsumer action) |
It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
V getOrDefault(Object key, V defaultValue) |
It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key. |
Set keySet( ) |
It returns a Set view of the keys contained in the map |
protected boolean removeEldestEntry(Map.Entry eldest) |
It returns true on removing its eldest entry. |
void replaceAll(BiFunction function) |
It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
Collection values() |
It returns a Collection view of the values contained in this map. |
Java TreeMap class is non-synchronized and maintains ascending order. It provides an efficient means of storing unique key-value pairs in sorted order(ascending order). Treemap will have null key but can have multiple null values. It implements the NavigableMap interface and extends AbstractMap class.
Use case demonstrating tree map
Methods available
Method |
Description |
Map.Entry ceilingEntry(K key) |
It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key. |
K ceilingKey(K key) |
It returns the least key, greater than the specified key or null if there is no such key. |
void clear() |
It removes all the key-value pairs from a map. |
Object clone() |
It returns a shallow copy of TreeMap instance. |
Comparator comparator() |
It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. |
NavigableSet descendingKeySet() |
It returns a reverse order NavigableSet view of the keys contained in the map. |
NavigableMap descendingMap() |
It returns the specified key-value pairs in descending order. |
Map.Entry firstEntry() |
It returns the key-value pair having the least key. |
Map.Entry floorEntry(K key) |
It returns the greatest key, less than or equal to the specified key, or null if there is no such key. |
void forEach(BiConsumer action) |
It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. |
SortedMap headMap(K toKey) |
It returns the key-value pairs whose keys are strictly less than toKey. |
NavigableMap headMap(K toKey, boolean inclusive) |
It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. |
Map.Entry higherEntry(K key) |
It returns the least key strictly greater than the given key, or null if there is no such key. |
K higherKey(K key) |
It is used to return true if this map contains a mapping for the specified key. |
Set keySet() |
It returns the collection of keys exist in the map. |
Map.Entry lastEntry() |
It returns the key-value pair having the greatest key, or null if there is no such key. |
Map.Entry lowerEntry(K key) |
It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. |
K lowerKey(K key) |
It returns the greatest key strictly less than the given key, or null if there is no such key. |
NavigableSet navigableKeySet() |
It returns a NavigableSet view of the keys contained in this map. |
Map.Entry pollFirstEntry() |
It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. |
Map.Entry pollLastEntry() |
It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. |
V put(K key, V value) |
It inserts the specified value with the specified key in the map. |
void putAll(Map map) |
It is used to copy all the key-value pair from one map to another map. |
V replace(K key, V value) |
It replaces the specified value for a specified key. |
boolean replace(K key, V oldValue, V newValue) |
It replaces the old value with the new value for a specified key. |
void replaceAll(BiFunction function) |
It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) |
It returns key-value pairs whose keys range from fromKey to toKey. |
SortedMap subMap(K fromKey, K toKey) |
It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive. |
SortedMap tailMap(K fromKey) |
It returns key-value pairs whose keys are greater than or equal to fromKey. |
NavigableMap tailMap(K fromKey, boolean inclusive) |
It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey. |
boolean containsKey(Object key) |
It returns true if the map contains a mapping for the specified key. |
boolean containsValue(Object value) |
It returns true if the map maps one or more keys to the specified value. |
K firstKey() |
It is used to return the first (lowest) key currently in this sorted map. |
V get(Object key) |
It is used to return the value to which the map maps the specified key. |
K lastKey() |
It is used to return the last (highest) key currently in the sorted map. |
V remove(Object key) |
It removes the key-value pair of the specified key from the map. |
Set> entrySet() |
It returns a set view of the mappings contained in the map. |
int size() |
It returns the number of key-value pairs exist in the hashtable. |
Collection values() |
It returns a collection view of the values contained in the map. |