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:
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsTo 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<>();
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.
It has four constructors, as mentioned below.
All of the below methods discussed here can be used irrespective of any version of Java.
HashMap is a Map-based collection class that is used for storing Key & value pairs. Let us look at a few examples.
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:
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:
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 MapcopyHashMap = 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.
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.
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 –
The above is the detailed content of HashMap in Java. For more information, please follow other related articles on the PHP Chinese website!