CodeToConcept
About

java

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

JavaHTMLCSS

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Java HashMap

HashMap is a class in Java that implements the Map interface.

It stores data as key-value pairs.

Key -> Value

For example:

101 -> Ashish
102 -> Rahul
103 -> Priya

HashMap belongs to the java.util package.

import java.util.HashMap;

Why do we use HashMap?

HashMap is commonly used when we need to:

  • Store data using unique keys.
  • Quickly retrieve values using keys.
  • Add, update, and remove key-value pairs.
  • Store data without requiring a particular iteration order.

For example:

import java.util.*;
 
public class HelloWorld {
    public static void main(String[] args) {
        HashMap<Integer, String> students = new HashMap<>();
 
        students.put(101, "Ashish");
        students.put(102, "Rahul");
        students.put(103, "Priya");
 
        System.out.println(students.get(102));
    }
}

Output

Rahul

Creating a HashMap

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

A more flexible approach is:

Map<Integer, String> map = new HashMap<>();

Here, the reference uses the Map interface while the object is a HashMap.

Adding Elements

Use put().

HashMap<Integer, String> map = new HashMap<>();
 
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

Updating a Value

If a key already exists, put() updates its value.

map.put(1, "Java Programming");

The previous value associated with key 1 is replaced.

Duplicate Keys

A HashMap does not allow duplicate keys.

map.put(1, "Java");
map.put(1, "Python");

The final mapping is:

1 -> Python

The second put() replaces the first value.

Duplicate Values

Duplicate values are allowed.

map.put(1, "Java");
map.put(2, "Java");

This is valid.

1 -> Java
2 -> Java

Retrieving a Value

Use get().

String value = map.get(1);
 
System.out.println(value);

Output

Java

Null Keys and Values

HashMap permits:

  • One null key.
  • Multiple null values.

Example

HashMap<Integer, String> map = new HashMap<>();
 
map.put(null, "Unknown");
map.put(1, null);
map.put(2, null);

This is valid for HashMap.

HashMap Does Not Guarantee Order

HashMap does not guarantee insertion order or sorted order.

For example:

HashMap<Integer, String> map = new HashMap<>();
 
map.put(3, "C");
map.put(1, "A");
map.put(2, "B");
 
System.out.println(map);

The displayed order should not be relied upon.

If insertion order is important, consider LinkedHashMap.

If sorted key order is required, consider TreeMap.

Iterating Through HashMap

Using entrySet()

for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(
        entry.getKey() + " -> " + entry.getValue()
    );
}

Using keySet()

for (Integer key : map.keySet()) {
    System.out.println(key);
}

Using values()

for (String value : map.values()) {
    System.out.println(value);
}

Important HashMap Methods

MethodPurpose
put()Adds or updates an entry
get()Retrieves a value
remove()Removes an entry
containsKey()Checks for a key
containsValue()Checks for a value
size()Returns number of entries
isEmpty()Checks whether map is empty
clear()Removes all entries
keySet()Returns keys
values()Returns values
entrySet()Returns entries
getOrDefault()Gets value or default
putIfAbsent()Adds when the key is absent or mapped to null

Example: Employee Information

HashMap<Integer, String> employees = new HashMap<>();
 
employees.put(101, "Ashish");
employees.put(102, "Rahul");
employees.put(103, "Priya");
 
System.out.println(employees.get(101));

Output

Ashish

Example: Counting Occurrences

A HashMap can also be used to count how many times an item appears.

String[] languages = {
    "Java", "Python", "Java", "C++", "Java"
};
 
HashMap<String, Integer> count = new HashMap<>();
 
for (String language : languages) {
    count.put(
        language,
        count.getOrDefault(language, 0) + 1
    );
}
 
System.out.println(count);

The map stores the frequency of each language.

Conceptually:

Java   -> 3
Python -> 1
C++    -> 1

HashMap Performance

For typical use cases, HashMap provides average constant-time performance for basic operations such as:

  • put()
  • get()
  • remove()
  • containsKey()

The exact performance can depend on hashing, collisions, and the internal structure.

HashMap vs LinkedHashMap

HashMapLinkedHashMap
No guaranteed iteration orderMaintains insertion order by default
General-purpose MapUseful when predictable iteration order is needed
Usually slightly less overheadMaintains additional links between entries
Allows one null keyAllows one null key

HashMap vs TreeMap

HashMapTreeMap
No guaranteed sorted orderKeys are sorted
Average O(1) basic lookup/updateO(log n) basic operations
Usually used for fast key-based accessUsed when sorted/navigable keys are required
Allows one null keyNatural ordering generally does not permit null keys

Is HashMap Thread-Safe?

HashMap is not synchronized.

If multiple threads modify the same map concurrently, appropriate synchronization or a concurrent collection such as ConcurrentHashMap may be needed.

Important Points

  • HashMap implements Map.
  • It stores key-value pairs.
  • Keys are unique.
  • Duplicate values are allowed.

One null key is allowed. Multiple null values are allowed. It does not guarantee insertion or sorted order. It is not synchronized. It is commonly used for fast key-based lookup.

Key Takeaway

Use HashMap when you need a general-purpose key-value data structure and do not need a guaranteed iteration order.

Map<Integer, String> map = new HashMap<>();

See you in next page....🙂

← OverviewLinkedHashMap →
← OverviewLinkedHashMap →