# HashMap in Java

**Introduction to HashMap**

`HashMap` is a Java class that implements the `Map` interface. It stores data as **key-value pairs**. Keys must be unique, but values can be duplicated. It does not guarantee insertion order.

### Syntax

```java
HashMap<KeyType, ValueType> map = new HashMap<>();
```

### Example

```java
import java.util.HashMap;

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

        students.put(1, "Mani");
        students.put(2, "Arun");
        students.put(3, "Priya");

        System.out.println(students);
    }
}
```

**How to Create a HashMap**

Create an empty HashMap using its constructor.

```java
HashMap<String, Integer> scores = new HashMap<>();
```

**How to Add Elements Using put()**

The `put()` method adds a key-value pair. If the key already exists, its value is replaced.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Arun");
students.put(1, "Priya");

System.out.println(students); // {1=Priya, 2=Arun}
```

**How to Access Values Using get()**

The `get()` method returns the value associated with a key.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");

System.out.println(students.get(1)); // Mani
```

**How to Check Keys Using containsKey()**

The `containsKey()` method checks whether a key exists.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");

System.out.println(students.containsKey(1)); // true
```

**How to Check Values Using containsValue()**

The `containsValue()` method checks whether a value exists.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");

System.out.println(students.containsValue("Mani")); // true
```

**How to Remove Elements Using remove()**

The `remove()` method removes an entry using its key.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Arun");

students.remove(1);

System.out.println(students); // {2=Arun}
```

**How to Update Values Using replace()**

The `replace()` method updates the value associated with an existing key.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.replace(1, "Arun");

System.out.println(students.get(1)); // Arun
```

**How to Find the Size Using size()**

The `size()` method returns the number of key-value pairs.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Arun");

System.out.println(students.size()); // 2
```

**How to Check Whether a HashMap Is Empty**

The `isEmpty()` method returns `true` if the map contains no entries.

```java
HashMap<String, Integer> scores = new HashMap<>();

System.out.println(scores.isEmpty()); // true
```

**How to Remove All Entries Using clear()**

The `clear()` method removes all key-value pairs.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.clear();

System.out.println(students); // {}
```

**How to Iterate Through a HashMap**

Use `entrySet()` to access keys and values together.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Arun");

for (var entry : students.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}
```

The iteration order is not guaranteed.

**How to Get All Keys and Values**

Use `keySet()` to retrieve keys and `values()` to retrieve values.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Arun");

System.out.println(students.keySet()); // Contains 1, 2
System.out.println(students.values()); // Contains Mani, Arun
```

**Does HashMap Allow Duplicate Keys?**

No. Keys must be unique. Adding an existing key replaces its previous value.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(1, "Arun");

System.out.println(students.get(1)); // Arun
```

**Does HashMap Allow Duplicate Values?**

Yes. Different keys can have the same value.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.put(2, "Mani");

System.out.println(students.size()); // 2
```

**Does HashMap Allow Null Keys and Values?**

Yes. HashMap allows one `null` key and multiple `null` values.

```java
HashMap<String, String> map = new HashMap<>();

map.put(null, "Java");
map.put("A", null);
map.put("B", null);

System.out.println(map);
```

**How to Set a Default Value Using getOrDefault()**

The `getOrDefault()` method returns a default value when the key does not exist.

```java
HashMap<String, Integer> scores = new HashMap<>();

scores.put("Mani", 90);

System.out.println(scores.getOrDefault("Arun", 0)); // 0
```

**How to Add a Value Using putIfAbsent()**

The `putIfAbsent()` method adds a mapping only if the key is absent or currently mapped to `null`.

```java
HashMap<Integer, String> students = new HashMap<>();

students.put(1, "Mani");
students.putIfAbsent(1, "Arun");
students.putIfAbsent(2, "Priya");

System.out.println(students); // Contains 1=Mani and 2=Priya
```

**How to Merge Values Using merge()**

The `merge()` method combines a new value with an existing non-null value using a function.

```java
HashMap<String, Integer> counts = new HashMap<>();

counts.merge("Java", 1, Integer::sum);
counts.merge("Java", 1, Integer::sum);

System.out.println(counts.get("Java")); // 2
```

**HashMap vs LinkedHashMap vs TreeMap**

| Feature | HashMap | LinkedHashMap | TreeMap |
| --- | --- | --- | --- |
| Data | Key-value pairs | Key-value pairs | Key-value pairs |
| Order | Not guaranteed | Insertion order by default | Sorted by key |
| Null keys | One allowed | One allowed | Generally not with natural ordering |
| Typical get/put time | Average O(1) | Average O(1) | O(log n) |

**Important HashMap Methods**

| Method | Purpose |
| --- | --- |
| `put()` | Adds or updates an entry |
| `get()` | Retrieves a value |
| `getOrDefault()` | Returns a value or default |
| `putIfAbsent()` | Adds if absent or mapped to null |
| `containsKey()` | Checks a key |
| `containsValue()` | Checks a value |
| `remove()` | Removes an entry |
| `replace()` | Updates an existing value |
| `merge()` | Combines values |
| `keySet()` | Returns the keys |
| `values()` | Returns the values |
| `entrySet()` | Returns key-value entries |
| `size()` | Returns the number of entries |
| `isEmpty()` | Checks whether the map is empty |
| `clear()` | Removes all entries |

**What Is the Time Complexity of HashMap?**

| Operation | Average Time Complexity |
| --- | --- |
| `put()` | O(1) |
| `get()` | O(1) |
| `remove()` | O(1) |
| `containsKey()` | O(1) |
| `containsValue()` | O(n) |
| Iteration | O(n) |

*Note: Hash-based operations can be slower in collision-heavy cases.*

**Conclusion**

`HashMap` is a Java Collection used to store and retrieve data through key-value pairs.

Key points to remember:

*   Keys are unique, but values can be duplicated.
    
*   One `null` key and multiple `null` values are allowed.
    
*   Insertion order is not guaranteed.
    
*   `put()`, `get()`, and `remove()` typically take O(1) average time.
    
*   Use `LinkedHashMap` to preserve insertion order and `TreeMap` to sort entries by key.
    

Where have you used `HashMap` in your Java projects, and what problem did it solve?
