Java HashMap Examples

Tags: , ,

In this post, I walk through the concept of Java HashMap, and use examples to describe its usage cases. 

What is HashMap

Java HashMap is a Hash table based implementation of the Java Map interface.  It provides all of the optional map operations, and permits null values and the null key.  The order of Keys in a HashMap is not guaranteed. So we should not reply on the order of the keys in a HashMap. 

HashMap vs Hashtable

Based on java doc, Java HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. For Hashtable, Any non-null object can be used as a key or as a value.

Since HashMap is unsynchronized, it is not thread-safe.  If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

For both HashMap and HashTable,  the objects used as keys must implement the hashCode method and the equals method.

See this post for the comparison of Java HashMap, Hashtable, TreeMap and SortedMap.

Java HashMap Methods 

Here are the list of methods implemented by java HashMap.

The most frequently used HashMap methods:

clear()
Removes all of the mappings from this map. The map will be empty after this call returns.

containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

size()
Returns the number of key-value mappings in this map.

Collection<V> values()
Returns a Collection view of the values contained in this map.

get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

put(K key, V value)
Associates the specified value with the specified key in this map.

isEmpty()
Returns true if this map contains no key-value mappings.

remove(Object key)
Removes the mapping for the specified key from this map if present.

keySet()
Returns a Set view of the keys contained in this map.

Set<Map.Entry<K,V>> entrySet()
Returns a Set view of the mappings contained in this map.

Here are less frequently used HashMap methods:

compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
Attempts to compute a mapping for the specified key and its current mapped value (or nullif there is no current mapping).

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

computeIfPresent(K key, BiFunction<? super K,? super V,? extendsV> remappingFunction)
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

forEach(BiConsumer<? super K,? super V> action)
Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

getOrDefault(Object key, V defaultValue)
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

merge(K key, V value, BiFunction<? super V,? super V,? extendsV> 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.

putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map.

putIfAbsent(K key, V value)
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

remove(Object key, Object value)
Removes the entry for the specified key only if it is currently mapped to the specified value.

replace(K key, V value)
Replaces the entry for the specified key only if it is currently mapped to some value.

replace(K key, V oldValue, V newValue)
Replaces the entry for the specified key only if currently mapped to the specified value.

replaceAll(BiFunction<? super K,? super V,? extends V> function)
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.

Java HashMap Usage Examples

The most popular example to use Java HashMap is the word count example.

How to get all keys from a HashMap?

The output:

get all the keys as a set
[David, Jack, Lily, Jim, Mary]

Get all the key value paris from hashMap
key = David [email protected]
key = Jack [email protected]
key = Lily [email protected]
key = Jim [email protected]
key = Mary [email protected]

How to define my own key  for HashMap

In the following example, we define a class named User, which contains name, email, age information. We map a user to his or her order Id. 

The output:

In hashcode
In hashcode
In hashcode
In hashcode
In hashcode
call equals for USER<Lily 23 [email protected]>
{USER<Jack 23 [email protected]> =21, USER<Lily 12 [email protected]> =35, USER<Jim 12 [email protected]> =34, USER<Lily 23 [email protected]l.com> =50}