Introduction

Java is known for its diverse offerings. From a vast variety of libraries to various features, Java provides it all. One such useful feature is the HashMap. HashMap is a dictionary data structure provided by Java. It is a Map-based collection class used to store data in pairs of a key and its corresponding value. Being a very useful feature, we are supposed to have an effective HashMap Java implementation for its proper utilization.

Why HashMap Java Implementation Should Be Done?

The primary benefit of using a HashMap in Java is relatively faster data retrieval. Developers can hash a key by implementing a hashing algorithm and relate it with the data index in memory to retrieve it faster. Beginners and amateur Java developers often find HashMap Java implementation to be a bit difficult and lengthy process due to countless long and complicated methods of HashMap Java implementation available online.

We will be discussing some basic steps you need to know to start with HashMap Java implementation. Later, you can further work on different hashing algorithms or more efficient HashMap Java implementation, but these steps will work as a foundation in learning HashMap implementation in Java.

· Create And Add An Object In A HashMap In Java

The first thing, we need to do is to create and add an object to the Maps. Always use Generics; a simple line of the following code will create HashMap with keys of String data type and values of Integer data type with default sizes and load factor (percentage of size, which if filled trigger resizes of HashMap).

HashMap<String, Integer> cache = new HashMap<String, Integer>();

You can also create a HashMap by copying the data from another Map or even from a hashtable.

See the following example:

HashMap<Integer, String> root = new HashMap<Integer,String>();

HashMap<Integer, String>  map = new HashMap(root);

You can also supply a load factor of your choice and initial capacity while creating an instance by using an overloaded constructor provided by the API. Adding elements in element is also called ‘’the put method’’ in HashMap. It requires a key and a value as parameters.

Following is an example of adding key and value while HashMap Java implementation:

HashMap.put(86, "Eighty Six");

Here, 86 is the key and “Eighty Six” is the value.

· Getting Value From The HashMap

To retrieve values from the HashMap, we first need to know the key object. We will be implementing this with the key inserted in the HashMap in the last example, for retrieving the value from a Map.

We use the get(key) method to get the value from HashMap :

Integer key = 86;

String value = HashMap.get(key);System.out.println("Key is " + key +" value returned is "+ value); 

Output:

Key is 86 value returned is Eighty Six

· How to Iterate in HashMap

The simple way to get multiple values from a HashMap is by iterating over the whole Map. In certain cases, it will be required to loop through the complete map to perform operations on each pair of keys and values, we can use the simple FOR or WHILE loop as an iterator for that.

For using an Iterator in HashMap Java implementation, first you need the set of keys, which can be retrieved using the method called map.keySet(). There are multiple ways to loop through a HashMap in HashMap Java implementation but we will be using the most common one.

Following is an example of iterating a HashMap using java.util.Iterator :

HashMap.put (86, "Eighty Six");

HashMap.put(121, "One Hundred And Twenty One");

HashMap.put(96, "Ninety Six");       

Iterator<Integer> keySetIterator = HashMap.keySet().iterator();

while(keySetIterator.hasNext()){  Integer key = keySetIterator.next();  

System.out.println("Key is " + key +" value returned is "+ value);

 } 

Output:

Key is 86 value returned is Eighty Six

Key is 121 value returned is One Hundred And Twenty One

Key is 96 value returned is Ninety Six

· Use Of Size() And Clear() Methods In HashMap

Two very simple tasks that you will be performing in the HashMap are finding out how many elements are stored in it. It is the number of values you have in your HashMap and clearing the HashMap to reuse it. Both of them are more or less used together. A Java Collection API will be required for performing any of these two jobs while Java HashMap implementation as it provides two methods called size() and clear() to perform these operations on java.util.HashMap.

See the following code example:

System.out.println("Size of Map: " + HashMap.size());

HashMap.clear(); //this method clears out HashMap , removeing all the element

System.out.println("Size of Map: " + HashMap.size());  

Output:

Size of Map: 3

Size of Map: 0

You can easily reuse an existing HashMap by clearing it, but make sure it is not being shared between multiple threads. It is always recommended to not do it until you have a genuine reason for doing it.

· Using Of Containskey() And Containsvalue() Functions In HashMap

In certain cases, you might not be performing a HashMap java implementation, but instead, you will come across an already made HashMap. You will be unaware of whether that HashMap contains an object as a key or as a value. java.util.HashMap library provides some convenient methods to find that out. containsKey( Object key ) and containsValue(Object value) methods can be used to check if any key value is present in the HashMap.

Both of these functions compares your passed parameter with every key or value and returns a Boolean value indicating that your passed value is present in the HashMap or not.

See this example:

System.out.println("Is there 86 as a key in this HashMap? ") 
HashMap.containsKey(86));

System.out.println("Is there 11 as a key in this HashMap? ") 
HashMap.containsValue(11));

System.out.println("Is there a Value, “The Hundred And Twenty One” in this HashMap? ")
HashMap.containsValue("One Hundred And Twenty One")); 

System.out.println("Is there a Value, “Twenty Seven” in this HashMap? ")
HashMap.containsValue("Twenty Seven"));  

Output:

Is there 86 as a key in this HashMap?
True

Is there 11 as a key in this HashMap?
False

Is there a Value, “The Hundred And Twenty One” in this HashMap? 
True 

Is there a Value, “Twenty Seven” in this HashMap? 
False

 

· How To Check If A HashMap Is Already Empty In Java

There are two simple ways to find out if a HashMap is empty, the first one is using the size() method that we have already discussed. If it returns 0, it means the HashMap is empty.

The second way is using a method primarily designed for it called isEmpty()which returns true if Map is empty else False.

Here is a code snippet:

boolean isEmpty;

isEmpty = HashMap.isEmpty();

System.out.println("Is this HashMap empty? " + isEmpty); 

Output:

Is this HashMap empty? : false

· Removing Objects From HashMap Example

After a successful HashMap Java implementation, you might also want to remove an entry from the created HashMap. The java.util.HashMap provides a method called remove(Object key) which takes the key as a parameter and removes its corresponding value from the HashMap.

The method will either return null or present the value of the entry that is just removed.

Here is an example code of removing a key value from the HashMap:

Integer key = 86;

Object value;

value = HashMap.remove(key);

System.out.println(value + "is removed from the HashMap. "); 



Output:

Eighty Six is removed from the HashMap.

· Sorting Data In A HashMap In Java

HashMap is an unsorted data structure by default in Java in which neither keys nor values are sorted. If it is required to sort data in HashMap, you can sort either based on keys or values. Keep in mind that there are no methods like Collections.sort() defined for a HashMap. It is only for List and its other implementations like ArrayList or LinkedList. So, to compare each value you will have to write an extensive code and then sort it as per your requirement.

Alternatively, you can also use a SortedMap in Java, like TreeMap. TreeMap comes with a constructor that accepts the Map and creates a Map sorted in the ascending order of key or any custom order defined by Comparator.

See this code example of sorting HashMap in Java by using a TreeMap in the ascending order of keys:

HashMap.put(181, "Hundred and Eighty One");

HashMap.put(102, "Hundred and Two");

HashMap.put(163, "Hundred and Sixty Three");

System.out.println("Unsorted HashMap values: " + HashMap);

TreeMap sortedHashMap = new TreeMap(HashMap);

System.out.println("Sorted HashMap: " + sortedHashMap);




Output:

Unsorted HashMap values: {181= Hundred and Eighty One, 102= Hundred and Two, 163= Hundred and Sixty Three}

Sorted HashMap Values: {102= Hundred and Two, 163= Hundred and Sixty Three, 181= Hundred and Eighty One}

· HashMap Synchronization In Java

If you want to use a HashMap in a multi-threaded environment, you will need to perform synchronization during HashMap Java implementation.

The method Collections.synchronizedMap(map) is used to synchronize a HashMap in Java. This method will return a thread-safe version of your HashMap and all the map operations will be serialized.

What is Collision in HashMap?

There are some limitations that you will probably encounter later when you will be extensively performing HashMap implementations in Java, one of which will be Collison between keys. The reason that an efficient HashMap Java implementation is required is because when you are dealing with a relatively bigger HashMap, there are always chances of generation of the same key for multiple values.

How to Avoid the Collision?

In all the above examples, we have manually assigned a unique key to each value, but it is not possible when you will be dealing with a HashMap consisting of thousands of values. In that case, you would be needing a hash function that generates a key according to its corresponding value. There is a possibility that multiple hashes can get the same hash key, thus resulting in a Collison. To resolve that, a container (bucket) is used which can store multiple key-value pairs. In HashMap, a bucket is comprised of simple LinkedList to store objects that come in handy in case of two keys having the same hashcode.

Along with that, the use of the equals() method for the key object also become very useful to check for the same keys. The bucket is a LinkedList but not the one in java.util.Linkedlist. HashMap has its different implementation of the LinkedList. It first traverses through LinkedList and compares all keys using keys.equals() until the equals() method returns true. This is when the value object is returned. Now to resolve that, the previous key-value pair is replaced with the current key-value pair.

What is Hashcode?

In HashMap, the get(key) method implicitly calls the hashCode() method on the key object and uses the returned Value to find the bucket location where the keys and values are stored. As discussed before, the get(key) method also checks if the key is null.

A null key is not an issue but there can be only one null key in HashMap, if a key is null, then it will always map to hash 0, and then ultimately to index 0 where the value will be saved so null will be used as a unique value here. If the key is not null, then the hashcode() function will be called for that key to generate a hash value.

Now, the hash value will be used to find the bucket location where the object is stored.

What are Capacity and Load Factor?

It is important to know for HashMap Java implementation that a single instance of a HashMap has two attributes that can affect the performance, the initial capacity and load factor.

The capacity is the frequency of buckets in the HashMap and the initial capacity is the capacity of the bucket when the HashMap was created.

The load factor is a value that tells how much space a HashMap has before it needs to increase its capacity automatically. When the number of objects in the HashMap exceeds the product of the load factor and the current capacity, the HashMap is then rehashed automatically which results in twice the number of buckets than before. In the HashMap class, the default value of the load factor is 0.75.

See Also: Java Getters and Setters: Basics, Common Mistakes, and Best Practices

Conclusion

This article has covered all the basics about how HashMap Java implementation is done. It also sheds some light on how a HashMap works internally in Java. You can further explore the applications of HashMap to be applied in your enterprise level projects and learn how it can be useful to you.

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment