Home > Java > javaTutorial > body text

HashMap in Java

王林
Release: 2024-08-30 15:34:13
Original
236 people have browsed it

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 Tests

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> ();
Copy after login

Where datatypeOfkey and dataytpeOfValue can be Integer or String.

Example:

Map<String, String> newHashMap = new HashMap<>();
Copy after login

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.

  1. HashMap(): It is the default one with a load factor of 0.75 and a capacity of 16.
  2. HashMap(int ): Creates HashMap with the capacity defined in its arguments. The load factor is the default here.
  3. HashMap(int , float ): Creates HashMap with the capacity and load factor defined in its arguments.
  4. HashMap(Map 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.

  1. public value get(Object key): Used to get the value of the corresponding key.
  2. public value put(K key, V value): Inserts the value which is mentioned in the argument for the corresponding key.
  3. public boolean containsKey(Object key): Decision of whether the key is present or not, note that the return type is Boolean.
  4. public boolean containsValue(Object value): Decision of whether the value is present or not, note that the return type is Boolean.
  5. public V remove(Object key): Clears particular key and its value-form HashMap as specified in code.
  6. public void clear(): Clears all keys and values from the HashMap as mentioned.
  7. public boolean isEmpty(): Verifies whether HashMap is empty or not.
  8. Object clone(): Mappings of a HashMap are returned by this method to use for cloning purposes to another HashMap.
  9. public int size(): Returns the size, means, how many key-value pair is present in a HashMap.
  10. public Set> entrySet(): The set of mapping in HashMap is returned by this method.
  11. public Set keySet(): The key set in HashMap is returned by this method.
  12. public void putAll(Map ): Copies whole map content to the other.
  13. 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);
}
}
Copy after login

Output:

HashMap in Java

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));
}
}
}
Copy after login

Output:

HashMap in Java

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 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());
}
}
Copy after login

Output:

HashMap in Java

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 –

  1. HTML Frames
  2. HTML Attributes
  3. What is JVM?
  4. Java ClassNotFoundException

The above is the detailed content of HashMap in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!