Maps and HashMaps

Last modified date

Comments: 0

The Map interface is an object that maps keys to values.



The putIfAbsent() method attempts to add a key-value pairing to the map if it is not already present.

If the key is not present, it adds it to the map and then returns null.

If the key is present, it will not update the value, but just return the original value already in the map.

In the example above, when an attempt is made to add a new value for an existing key, the original key-value pairing is preserved in the map and the original value is returned.


The computeIfPresent() method attempts to apply a function to a value in a map if the key is already present.

In this word count example, the putIfAbsent will return the key value if it already exists in the map. Then the computeIfPresent method gets the value from the map and applies the increment v+1 function to the value.


The computeIfAbsent() method attempts to compute a value for a key if it is not present in the map.

If the key exists in the map, it returns value and operation can be formed on the value, else it will apply the function provided.

In the example above, if the key is absent in the map, the key is inserted with a new HashSet as the value and then the add operation adds the first word into the HashSet.

But if the key already exists, the value is returned for the key and the add operation is then performed on the value instead of a new HashSet being created.

HashMap Implementation

There are two different ways a HashMap can be implemented:

Direct Chaining (Sticking Out Strategy)

This strategy uses a Linked List to store entries with the same hash value.

Tucked in Strategy

The tucked in strategy works such that if the position is occupied, different fallback positions are tried to store the value.

Time Complexity

OperationTime Complexity
Look UpO(1)


Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.