Creating and Using HashMap in Java with Examples

  • 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().

import java.util.HashMap;

public class IterateMap {
    public static void main(String[] args) {
        HashMap<String, String> capitals = new HashMap<>();
        capitals.put("India", "New Delhi");
        capitals.put("USA", "Washington");
        capitals.put("France", "Paris");

        for (String country : capitals.keySet()) {
            System.out.println("The capital of " + country + " is " + capitals.get(country));
        }
    }
}
OUTPUT:
The capital of India is New Delhi 
The capital of USA is Washington 
The capital of France is Paris

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top