Author Topic: Explanation of Hashmap in java with example  (Read 4129 times)

Musfiqur Rahman

  • Newbie
  • *
  • Posts: 45
    • View Profile
    • Musfiqur Rahman
Explanation of Hashmap in java with example
« on: March 23, 2023, 01:44:54 PM »
HashMap is a class in Java that provides a way to store and retrieve key-value pairs in a map-like data structure. HashMap is part of the Java Collections Framework and is widely used in Java programming.

Here's an example of how to use HashMap in Java:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // create a new HashMap
        HashMap<String, Integer> map = new HashMap<>();

        // add key-value pairs to the HashMap
        map.put("apple", 10);
        map.put("banana", 5);
        map.put("orange", 8);

        // get the value associated with a key in the HashMap
        int appleCount = map.get("apple");
        System.out.println("Number of apples: " + appleCount);

        // update the value associated with a key in the HashMap
        map.put("apple", 15);
        System.out.println("Updated HashMap: " + map);

        // remove a key-value pair from the HashMap
        map.remove("banana");
        System.out.println("Updated HashMap: " + map);
    }
}

In this example, we create a new HashMap of type String keys and Integer values, add some key-value pairs to it, get the value associated with a key, update the value associated with a key, and remove a key-value pair from the HashMap. Here's the output of the program:

Number of apples: 10
Updated HashMap: {orange=8, apple=15, banana=5}
Updated HashMap: {orange=8, apple=15}

The HashMap class provides many other useful methods for working with key-value pairs, such as putAll, containsKey, containsValue, keySet, values, entrySet, and more. You can also create HashMaps with keys and values of other types, such as Integer keys and String values. Overall, HashMaps provide a flexible and powerful way to manage key-value pairs in Java.