Introduction to HashMap in Java
In Java, you can use the array to store data, but whenever there is a requirement to store or retrieve data in a key and value fashion, you have to use HashMap for that. Hashmap is a collection in Java that belongs under the hierarchy of the interface called Map. In this article, we will discuss the Hashmap from Java programming’s perspective.
Syntax:
To use HashMap in your code, you must import (import java.util.HashMap package) or its parent class.
import java.util.HashMap;
import java.util.Map;
HashMap<datatypeOfkey, dataytpeOfValue> <name_of_hashMap> =new HashMap<datatypeOfkey, dataytpeOfValue> ();
Where datatypeOfkey and dataytpeOfValue can be Integer or String.
Example:
Map<String, String> newHashMap = new HashMap<>();
How does HashMap work in Java?
Hashmap uses hashing techniques to store and retrieve elements. For storage, it uses a linked list which is referred to as buckets. It uses two methods on the key: equals()and hashCode() for insert and retrieves operations. While insertion, hashCode determines the bucket for storing. After that, again, hashCode checks whether there is already a key with equal hashCode; if yes, the value is replaced with the new one. If not, then the new map is created into which value will be stored. While retrieval of data, hashCode determines the bucket for searching. After that, hashCode() and equals() gets the value and returns that. It returns null in case no value is present.
HashMap Constructor in Java
It has four constructors, as mentioned below.
- HashMap(): It is the default one with a load factor of 0.75 and a capacity of 16.
- HashMap(int <capacity>): Creates HashMap with the capacity defined in its arguments. The load factor is the default here.
- HashMap(int <capacity>, float <load_Factor>): Creates HashMap with the capacity and load factor defined in its arguments.
- HashMap(Map<K, V> m): Creates HashMap as defined in the argument map.
Top 13 Methods of HashMap in Java
All of the below methods discussed here can be used irrespective of any version of Java.
- public value get(Object key): Used to get the value of the corresponding key.
- public value put(K key, V value): Inserts the value which is mentioned in the argument for the corresponding key.
- public boolean containsKey(Object key): Decision of whether the key is present or not, note that the return type is Boolean.
- public boolean containsValue(Object value): Decision of whether the value is present or not, note that the return type is Boolean.
- public V remove(Object key): Clears particular key and its value-form HashMap as specified in code.
- public void clear(): Clears all keys and values from the HashMap as mentioned.
- public boolean isEmpty(): Verifies whether HashMap is empty or not.
- Object clone(): Mappings of a HashMap are returned by this method to use for cloning purposes to another HashMap.
- public int size(): Returns the size, means, how many key-value pair is present in a HashMap.
- public Set<Map.Entry<K, V>> entrySet(): The set of mapping in HashMap is returned by this method.
- public Set<K> keySet(): The key set in HashMap is returned by this method.
- public void putAll(Map <map_name>): Copies whole map content to the other.
- Collection values(): You can get a collection of all of the values for a HashMap.
Examples of HashMap in Java
HashMap is a Map-based collection class that is used for storing Key & value pairs. Let us look at a few examples.
Example #1
We will discuss some code examples of HashMap here. You should practice codes by writing yourself and run on the java compiler to check the output. You can match the output with the given one for verification. Creation of HashMap and insertion of data in it.
Code:
import java.util.HashMap;
import java.util.Map;
public class CreateHashMapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, String> newHashMap = new HashMap<>();
// Addition of key and value
newHashMap.put("Key1", "Java");
newHashMap.put("Key2", "C++");
newHashMap.put("Key3", "Python");
// Addition of new key and value
newHashMap.putIfAbsent("Key4", "Ruby");
System.out.println(newHashMap);
}
}
Output:
Example #2
Let us take another example where we take a string as a key and an integer as a value. Here we will measure the key and its corresponding values in inch as value.
Code:
import java.util.HashMap;
public class CreateHashMapExample2 {
public static void main(String[] args) {
// Create a HashMap object called measurement
HashMap<String, Integer> ms = new HashMap<String, Integer>();
// Add keys and values (Name and phone number of the person)
ms.put("S", 35);
ms.put("M", 38);
ms.put("L", 40);
ms.put("XL", 42);
for (String key : ms.keySet()) {
System.out.println("measurement of " + key + " in inch is: " + ms.get(key));
}
}
}
Output:
Example #3
Here we will do multiple things. We will first create a Hashmap; we will then get its values one by one. After that, we will copy all data of the HashMap to a brand new HashMap. After that, we will remove one item and gets their sizes. If the size is lower by one, the decrease of size by removal is confirmed.
Code:
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class HashMapInJava {
public static void main(String[] args) {
Map<String, String> newHashMap = new HashMap<>();
// Addition of key and value
newHashMap.put("Key1", "Lenovo");
newHashMap.put("Key2", "Motorola");
newHashMap.put("Key3", "Nokia");
newHashMap.put("Key4", null);
newHashMap.put(null, "Sony");
System.out.println("Original map contains:" + newHashMap);
//getting size of Hashmap
System.out.println("Size of original Map is:" + newHashMap.size());
//copy contains of one Hashmap to another
Map<String, String> copyHashMap = new HashMap<>();
copyHashMap.putAll(newHashMap);
System.out.println("copyHashMap mappings= " + copyHashMap);
//Removal of null key
String nullKeyValue = copyHashMap.remove(null);
System.out.println("copyHashMap null key value = " + nullKeyValue);
System.out.println("copyHashMap after removing null key = " + copyHashMap);
System.out.println("Size of copyHashMap is:" + copyHashMap.size());
}
}
Output:
Did you notice one thing in the output of HashMap in all of our examples while we print the key and values? The print is not in sorted order. Hashmap is not like an array, so scan and print need to be sorted; it can pick random based on its hash value.
Conclusion
You should use HashMap when your code or use case requires the handling of data in key-value pairs. In this article, we have learned about hashmaps in Java with code examples. First, however, you should practice writing codes on your own to master this topic.
Recommended Article
This is a guide to the HashMap in Java. Here we discuss Introduction to HashMap in Java and its Methods along with Code implementation and Output. You can also go through our suggested articles to learn more –