Hashmap Example in Java
On this page (10sections)
Introduction
HashMap is a classic Java console program that demonstrates the concept with complete source code and sample output. The Collections Framework provides ArrayList, HashMap, HashSet and related data structures.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
A Hashmap is a Map data structure. Like a list each item that is stored in a hashmap is stored at a particular index. This index is called a hash and it is generated using a hash function. Hash functions accept the object to be stored as an argument and generate a number that is unique to it.
Syntax
HashMap Variable_name = new HashMap();
HashMap Example Program
import java.util.HashMap;
public class HashMapExample {
public static void main(String a[]){
HashMap hm = new HashMap();
hm.put("1","FIRST");
hm.put("2","SECOND");
hm.put("3","THIRD");
hm.put("4",null);
hm.put(null,"FIFTH");
System.out.println("hashmap is "+hm);
System.out.println("Value of 1: "+hm.get("1"));
System.out.println("Is HashMap empty? "+hm.isEmpty());
hm.remove("2");
System.out.println("After removal process, the hashmap is "+hm);
System.out.println("Size of the HashMap: "+hm.size());
}
}
Sample Output
hashmap is {null=FIFTH, 3=THIRD, 2=SECOND, 1=FIRST, 4=null}
Value of 1: FIRST
Is HashMap empty? false
After removal process, the hashmap is {null=FIFTH, 3=THIRD, 1=FIRST, 4=null}
Size of the HashMap: 4
When to use
Use this hashmap example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.HashMap;imports a class used later in the program. -
HashMap hm = new HashMap();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.