Understanding basics of HashMaps in Java
Tags: java, programming, tutorial, beginners
Published: 2023-06-21 17:09:04

## Introduction:

   A HashMap in Java is a data structure that allows you to store and retrieve key-value pairs efficiently. It works like a dictionary where each key is associated with a value. When you add a key-value pair to a HashMap, Java uses a hash function to compute a unique hash code for the key. This hash code is then used to determine the index at which the key-value pair will be stored in an underlying array.


## Table of contents

1.[Why Hashmap?](#chapter-1)
2.[How does HashMap works in java?](#chapter-2)
3.[Hashmap initialization](#chapter-3)
4.[Hashmap example](#chapter-4)
5.[Frequently used Hashmap Methods](#chapter-5)

## 1. Why HashMap?<a name="chapter-1" ><a>

   Let's assume a scenario where we need to declare multiple number of variables , of course we can assign each variable individually one by one but after certain number of variables declared it becomes clumsy and hard to keep track of the variables. So in order to solve this **Hashmap** comes into play. Hashmap assigns the variables and their values in **_key-Value pairs_** similar to dictionary in python.



## 2. How does HashMap works in java?<a name="chapter-2" ><a>


Here are some points to remember for Hashmaps in Java:

1. It does **not maintain any order.**
2. It is **non-synchronised.**
3. It may contain one or more null values.
4. Initially, the **default capacity** of the **Java Hashmap class is 16.**
5. The operation of storing and retrieving the object is done at a constant time, provided that the key is known. The method to store the object is put(key, value) and the method to retrieve the object is get(key).

There are following **_parameters_** in Java Hashmap:
K: the type of keys maintained by the map
V: the type of values mapped.

## 3. Hashmap initialization:<a name="chapter-3" ><a>


In java hashmaps can be initialization by following code snippet,


`HashMap<wrapperClass of Key, wrapperClass of Value> hash = new HashMap<String,Integer>();
`

Now what is this wrapper class? let's understand that,

A **wrapper class** is a class that provides a way to encapsulate primitive data types (such as int, char, boolean, etc.) into objects. Wrapper classes allow us to treat these primitive types as objects and provide additional functionality to them.

## 4. Hashmap example:<a name="chapter-4" ><a>


Let us take a scenario where we have to assign variables for a set of usernames and passwords, if we try to implement this without hashmaps it looks something like this,
       

```java
        String user1="person1";
        String password1="xxz";
        String user2="person2";
        String password2="xxxz";
        String user3="person3";
        String password3="xxxxz";
```
This looks ugly and this is not a good practice of coding. Let's implement the same using Hashmap.


```java
import java.util.HashMap; //importing hashmap package

public class hashmap {
    public static void main(String[] args) {

//initialization of hashmap by creating an instance

    HashMap<String,String> usersHash = new HashMap<String,String>();

//Using put method of hashmap to add new values in hashmap

    usersHash.put("person1","xxz");
    usersHash.put("person2","xxxz");
    usersHash.put("person3","xxxxz");

    System.out.println(usersHash);
    }
}

```

The output for the above example would be,

```
{person3=xxxxz, person2=xxxz, person1=xxz}
```

it returns a key-value pair.

It's as simple as that.!, Hashmap also has number of methods to perform various actions on the map.

## 5. Frequently used Hashmap Methods:<a name="chapter-5" ><a>


**boolean isEmpty()** - Return true if this map contains no 
                 key-value mappings.

**Object clone()** - Return a shallow copy of this HashMap 
                     instance: the keys and values themselves 
                     are not cloned.

**Set entrySet()** - Return a collection view of the mappings 
                     contained in this map.

**Set keySet()** - Return a set view of the keys contained in 
                   this map.

**V put(Object key, Object value)**  - It is used to insert 
                                       an entry in the map.

**putAll(Map map)** - Insert the specified map in the map.

**V remove(Object key)** - Delete an entry for the specified key.

I hope this post helps you to get a better understanding about hashmaps in java.
Happy coding...😉