Java HashMap

In Java, the HashMap is part of the java.util package and is one of the most widely used data structures. It allows you to store data in the form of key-value pairs, making it ideal for applications that require fast access to data.

In this post by The Coding College, we’ll dive into the fundamentals of HashMap, including its features, methods, and practical examples, ensuring the content aligns with Google E-E-A-T principles.

What is a HashMap?

A HashMap is a collection that implements the Map interface. It uses a hash table to store data, enabling quick access, retrieval, and updates. Keys in a HashMap must be unique, but values can be duplicated. Additionally, a HashMap allows one null key and multiple null values.

Key Features of HashMap

  1. Key-Value Pairs: Data is stored as pairs where each key maps to a specific value.
  2. Unique Keys: Duplicate keys are not allowed.
  3. Fast Access: Uses a hash table for quick data retrieval.
  4. Allows Nulls: One null key and multiple null values are allowed.
  5. Unordered: Elements are not stored in any specific order.

How to Use HashMap

To use a HashMap in Java, you must import the java.util.HashMap package.

Syntax:

HashMap<KeyType, ValueType> mapName = new HashMap<>();

Example: Creating a Simple HashMap

Code:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> studentMarks = new HashMap<>();

        // Add key-value pairs
        studentMarks.put("Alice", 85);
        studentMarks.put("Bob", 92);
        studentMarks.put("Charlie", 78);

        // Print the HashMap
        System.out.println("Student Marks: " + studentMarks);
    }
}

Output:

Student Marks: {Alice=85, Bob=92, Charlie=78}

HashMap Methods

Here are some commonly used methods of HashMap:

MethodDescription
put(key, value)Inserts a key-value pair into the map.
get(key)Retrieves the value associated with a key.
remove(key)Removes the key-value pair for the specified key.
containsKey(key)Checks if the map contains the specified key.
containsValue(value)Checks if the map contains the specified value.
keySet()Returns a set of all the keys in the map.
values()Returns a collection of all the values in the map.
isEmpty()Checks if the map is empty.
size()Returns the number of key-value pairs in the map.
clear()Removes all entries from the map.

Example: Common Operations with HashMap

Code:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> countries = new HashMap<>();

        // Add key-value pairs
        countries.put("India", "New Delhi");
        countries.put("USA", "Washington, D.C.");
        countries.put("UK", "London");

        // Get a value by key
        System.out.println("Capital of India: " + countries.get("India"));

        // Check if a key exists
        System.out.println("Does the map contain USA? " + countries.containsKey("USA"));

        // Check if a value exists
        System.out.println("Does the map contain London? " + countries.containsValue("London"));

        // Remove a key-value pair
        countries.remove("UK");
        System.out.println("Updated Map: " + countries);

        // Get the size of the HashMap
        System.out.println("Number of entries: " + countries.size());
    }
}

Output:

Capital of India: New Delhi
Does the map contain USA? true
Does the map contain London? true
Updated Map: {India=New Delhi, USA=Washington, D.C.}
Number of entries: 2

Real-Life Applications of HashMap

  1. Caching Data: HashMap is used to store frequently accessed data for quick lookups.
  2. Counting Frequency: Used for counting occurrences of elements in arrays or lists.
  3. Database-like Operations: Acts as an in-memory database for simple key-value storage.
  4. Mapping Configurations: Stores configurations or mappings (e.g., country and capital).

HashMap vs Other Maps

FeatureHashMapTreeMapLinkedHashMap
OrderingNo specific orderSorted orderInsertion order
Null KeysAllowed (only one)Not allowedAllowed (only one)
Null ValuesAllowedAllowedAllowed
PerformanceFast (O(1))Slower (O(log n))Slightly slower

Conclusion

The HashMap is a versatile and efficient data structure for storing and retrieving key-value pairs. Whether you’re working with configuration settings, caching, or simple mappings, HashMap is a go-to choice for Java developers.

Stay tuned to The Coding College for more in-depth tutorials and resources to advance your Java programming skills!

Leave a Comment