← Back to Chapters

HashMap in Advance Java

?️ HashMap in Advance Java

? Quick Overview

HashMap is a part of the Java Collection Framework that stores data in key-value pairs. It allows fast data retrieval using hashing technique and does not maintain insertion order.

? Key Concepts

  • Stores data as key → value pairs
  • Keys must be unique
  • Allows one null key and multiple null values
  • Not synchronized (not thread-safe)
  • Uses hashing for fast access

? Syntax & Theory

HashMap belongs to java.util package and implements the Map interface. It uses hash table internally to store data.

? View Code Example
// Creating a HashMap with Integer keys and String values
HashMap<Integer, String> map = new HashMap<>();

? Code Examples

? View Code Example
// Basic operations on HashMap
import java.util.HashMap;

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

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

students.put(101, "Amit");
students.put(102, "Rahul");
students.put(103, "Sneha");

System.out.println(students);

System.out.println(students.get(102));

students.remove(101);

System.out.println(students);
}
}

? Interactive Playground: HashMap Visualizer

Enter a key and value to see how put() and remove() update the map dynamically.

Map is empty
> System.out.println("HashMap initialized...");

? Live Output / Explanation

Output

The HashMap prints all key-value pairs. The get() method fetches the value using the key, and remove() deletes the specified entry.

? Tips & Best Practices

  • Use immutable objects as keys
  • Override equals() and hashCode() properly
  • Use ConcurrentHashMap for multithreading
  • Avoid excessive resizing by setting initial capacity

? Try It Yourself

  • Create a HashMap to store employee ID and salary
  • Check if a key exists using containsKey()
  • Iterate HashMap using entrySet()
  • Replace a value using replace()