CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Java – How to use HashMap collection?

HashMap is part of Java Collections, which has been first implemented in Java 1.2 version and has been in use since then. Java Collection Framework was introduced as a technique to store and operate on data with ease. This collection framework provides many interfaces and its implementations to operate on data with speed and efficiency in terms of space and time.

Java HashMap collection class

HashMap is a collection of data units, where each unit is a (Key, Value) pair. Every Key is associated with a Value and we make use Keys to retrieve these Values.

HashMap Implementation

HashMap implements the Map interface and extends the AbstractMap class. It uses a technique called hashing, to effectively store the (Key, Value) pairs, and hence the name.

Hashing is a technique that is used to make search operations faster. For example, hashing is done on the Keys, to convert larger strings into a smaller set of repetitive strings, which can then be used as indexes to store the values in the form of a hash table.

How do we create HashMaps?

HashMaps are part of java.util package and hence we need to import it into our program, to use HashMaps. HashMap contains only unique Keys but it can have duplicate Values. A Key can be a NULL only once, whereas Values can have multiple NULL values.

Unlike HashTables, HashMap does not maintain insertion order.

An instance of HashMap is created along with specifying the data types of Key and Value pairs as shown below;

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

The above declaration says that all the Keys should be Integers and all the Values should be Strings. The constructor used here is a default constructor and the instance of HashMap is created with some default capacity.

There are 3 more constructors for HashMap:

    1. HashMap(int Capacity) – The HashMap is created with the specified capacity.
    2. HashMap(Map M) – The HashMap is created and initialized with the elements in the Map instance M.
    3. HashMap(int initialCapacity, float loadFactor)HashMap instance is created with the specified capacity and load factor. By default, the load factor is set to 0.75.  As the capacity of the HashMap reaches to full, rehashing will be performed to increase the capacity of the HashMap, usually by a factor of 2. The Load factor is the measure which allows HashMap to fill to a certain capacity before performing rehashing. The load factor is set to 0.75 by default, which allows to maintain a balance between time and space complexities. When the number of elements in the HashMap becomes more than the product of the Load Factor and the initial capacity then rehashing will be performed.

Methods in HashMap

Below are the methods that will be used more frequently while working with HashMaps;

1. m.put(Key, Value) – Inserts a Key and Value pair into the HashMap.

2. m.putAll(M) – Inserts all the elements from the Map instance M, into the HashMap.

3. m.remove(Key) – All the values associated with the specified Key are removed.

4. m.get(Key) – It fetches the Value that is associated with the specified Key.

5. m.containsKey(Key) – This method checks if the specified Key is present in the HashMap and returns true if present else returns false.

6. m.containsValue(Value) – It checks if the specified Value is present in the HashMap and returns true if present else returns false.

7. m.isEmpty() – This method checks if the HashMap is empty or not and returns true if empty else returns false.

8. m.keySet() – It returns a Set, that contains all the Keys present in the HashMap.

9. m.values() – This method returns a Collection, that contains all the Values present in the HashMap.

10. m.size() – It returns the size of the HashMap.

11. m.replace(Key, Value) – This method replaces the specified Key’s value with the new Value.

12. m.clone() – It creates a shallow copy to the HashMap instance m.

13. m.getOrDefault(Key, DefaultValue) – It returns Value mapped to the specified Key and if there is no mapping present for the specified Key it returns the specified default value.

14. m.putIfAbsent(Key, Value) – This method associates the specified Value to the Key if there is no mapping present to that Key or if it is mapped to Null and returns null, else returns the current value.

There are few methods that are being inherited from it’s Base classes.

Inherited methods from AbstractMap class

equals(), hashCode() and toString() methods.

Inherited methods from Map interface

equals() and hashCode() methods.

Inherited methods from the parent class Object

finalize(), getClass(), notify(), notifyAll(), and wait() methods.

So far, we have seen the methods & the way we create HashMap objects. Let’s put all together into a sample program. Here is the working example;

import java.util.*;

public class HM {
	public static void main(String args[]) {
		HashMap < String, Integer > m = new HashMap < String, Integer > ();

		System.out.println("Initially map: " + m);
		m.put("Aisha", 98);
		m.put("Zakir", 80);
		m.put("Deva", 77);

		System.out.println("After insertion: " + m);
		System.out.println("Size of map: " + m.size());
		System.out.println("Key set: " + m.keySet());
		System.out.println("Values: " + m.values());
		System.out.println("Contains key Deva? " + m.containsKey("Deva"));
		System.out.println("Contains value 50? " + m.containsValue(50));

		m.clear();

		System.out.println("Map after clearing: " + m);
	}
}

Once we run this program; it will show the below result;

Output:

Initially map: {}
After insertion: {Aisha=98, Zakir=80, Deva=77}
Size of map: 3
Key set: [Aisha, Zakir, Deva]
Values: [98, 80, 77]
Contains key Deva? true
Contains value 50? false
Map after clearing: {}

Performance of HashMap

HashMap performs with a constant time complexity on all the insertion, search, retrieval and manipulation operations. The iteration through HashMap is directly proportional to its capacity and therefore it requires that the initial capacity is not too high.

Synchronization

HashMap is not synchronized by default and needs synchronization externally with the help of the method Collections.synchronizedMap().
HashMap is similar to HashTable except that HashTable is synchronized by default.

I hope you like this Article. Please give your feedback, in below Comments section. We will discuss more topics as we go.

Java – How to use HashMap collection?

Leave a Reply

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

Scroll to top
Exit mobile version