- Introduction
- Creating a HashMap in Java
- Accessing Elements in HashMap
- Iterating Through a HashMap
- Key Features of HashMap
In Java, a `HashMap` is used to store data in key-value pairs. It belongs to the `java.util` package and provides fast access to elements using keys. In this article, we will learn how to create, insert, access, and iterate over a HashMap with examples.
Creating a HashMap in Java
import java.util.HashMap; public class Example { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Python"); map.put(3, "C++"); System.out.println(map); } }
OUTPUT: {1=Java, 2=Python, 3=C++}
Key Features of HashMap
-
Keys must be unique.
-
Values can be duplicate.
-
Does not maintain any order.
-
Fast for search, insert, and delete.
Accessing Elements in HashMap
use the .get(key)
method to access values.
import java.util.HashMap; public class AccessMap { public static void main(String[] args) { HashMap<String, Integer> ages = new HashMap<>(); ages.put("Alice", 25); ages.put("Bob", 30); System.out.println("Alice's age is: " + ages.get("Alice")); } }
OUTPUT: Alice's age is: 25
Iterating Through a HashMap
can loop through the map using a for-each
loop and keySet()
or entrySet()
.