US Trends

what is hashmap in java

What is HashMap in Java

A **HashMap** in Java is a data structure that stores data as **key-value pairs**. You use a **key** to quickly find its related **value** , which makes it very useful for lookups, counting, and mapping one thing to another.

Quick Scoop

  • HashMap is part of the java.util package and implements the Map interface.
  • Keys must be unique , but values can repeat. If you insert the same key again, the new value replaces the old one.
  • It allows one null key and multiple null values.
  • It is commonly used when you need fast access to data by key, such as a phone book, word counts, or user ID lookups.

How it works

HashMap uses hashing to decide where to store a key-value pair internally, which helps make basic operations like put(), get(), and remove() efficient.

When two keys end up in the same bucket, Java handles the collision with a linked list or, in newer Java versions, a balanced tree.

Simple example

java

import java.util.HashMap;

HashMap<String, String> phoneBook = new HashMap<>();
phoneBook.put("Alice", "1-800-ALICE");
phoneBook.put("Bob", "1-800-BOB");

System.out.println(phoneBook.get("Bob")); // 1-800-BOB

In this example, "Bob" is the key and "1-800-BOB" is the value.

When to use it

Use a HashMap when you want:

  • Fast lookup by key.
  • Easy storage of related data.
  • A structure for things like frequency counting, caching, or ID-to-object mapping.

One important note

HashMap is not thread-safe by default, so if multiple threads need shared access, developers often use alternatives like ConcurrentHashMap.

If you want, I can also give you:

  • a 1-line definition ,
  • a difference between HashMap and Hashtable , or
  • a beginner-friendly Java example.