Introduction to HashMaps in Java

Introduction to HashMaps

Hi, and welcome! Today, we'll explore HashMaps, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment.

Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of HashMaps! Today, we'll understand HashMaps and learn how to implement them in Java.

Understanding HashMaps

HashMaps are special types of data structures that utilize unique keys instead of indexes. When you know the key (toy's label), you can directly pick up the value (toy). That's how a HashMap works!

Consider an oversized library of books. With HashMaps (which act like the library catalog), you'll quickly locate any book using a unique number (key)!

HashMaps in Java: HashMap

Java implements HashMaps through the HashMap class in the java.util package. They hold data in key-value pairs.

Let's create a HashMap, functioning as a catalog for a library:

import java.util.HashMap;
import java.util.Map;

class Solution {
    public static void main(String[] args) {
        // Creating a catalog for the library using HashMap with initialization
        Map<String, String> libraryCatalog = new HashMap<>(Map.of(
            "book1", "A Tale of Two Cities",
            "book2", "To Kill a Mockingbird",
            "book3", "1984"
        ));
    }
}

In this HashMap, book1, book2, and book3 are keys, while the book titles serve as their respective values.

It's important to remember that the keys should be of a type that supports hashing and equality comparison. Examples include String, Short, Integer, Long, Float, Double, Character, and Boolean. The values can be of any type.

HashMap Operations: Accessing, Updating, and Removing Elements

HashMap allows you to access, update, or remove elements:

  1. Accessing Elements: You can retrieve a book's title using its key straightforwardly: libraryCatalog.get("book1") would return "A Tale of Two Cities." But what happens if you try to access a key that isn't present in the HashMap? This would return null.

    import java.util.HashMap;
    import java.util.Map;
    
    class Solution {
        public static void main(String[] args) {
            // Creating a catalog for the library using HashMap with initialization
            Map<String, String> libraryCatalog = new HashMap<>(Map.of(
                "book1", "A Tale of Two Cities",
                "book2", "To Kill a Mockingbird",
                "book3", "1984"
            ));
    
            // Accessing a book's title
            String title1 = libraryCatalog.get("book1");
            if (title1 != null)
                System.out.println(title1); // Output: "A Tale of Two Cities"
            else
                System.out.println("Key not found");
    
            // Accessing a nonexistent key
            String titleNonexistent = libraryCatalog.get("book100");
            if (titleNonexistent != null)
                System.out.println(titleNonexistent);
            else
                System.out.println("Key not found"); // Output: "Key not found"
        }
    }
  2. Adding or Updating Elements: Whether you're adding a new book to the catalog or updating an existing book's title, you'll use the put() method.

    If the specified key exists in the HashMap, the assigned value replaces the existing one. For updating a title: libraryCatalog.put("book1", "The Tell-Tale Heart").

    If the key doesn't exist in the HashMap yet, the operation creates a new key-value pair. For adding a new book: libraryCatalog.put("book4", "Pride and Prejudice").

    import java.util.HashMap;
    import java.util.Map;
    
    class Solution {
        public static void main(String[] args) {
            // Creating a catalog for the library using HashMap with initialization
            Map<String, String> libraryCatalog = new HashMap<>(Map.of(
                "book1", "A Tale of Two Cities",
                "book2", "To Kill a Mockingbird",
                "book3", "1984"
            ));
    
            // Updating an existing book's title
            libraryCatalog.put("book1", "The Tell-Tale Heart");
            System.out.println("Updated book1: " + libraryCatalog.get("book1")); // Output: "Updated book1: The Tell-Tale Heart"
    
            // Adding a new book to the catalog
            libraryCatalog.put("book4", "Pride and Prejudice");
            System.out.println("Added book4: " + libraryCatalog.get("book4")); // Output: "Added book4: Pride and Prejudice"
        }
    }
  3. Removing Elements: If book1 no longer exists, you can remove it using libraryCatalog.remove("book1").

    import java.util.HashMap;
    import java.util.Map;
    
    class Solution {
        public static void main(String[] args) {
            // Creating a catalog for the library using HashMap with initialization
            Map<String, String> libraryCatalog = new HashMap<>(Map.of(
                "book1", "A Tale of Two Cities",
                "book2", "To Kill a Mockingbird",
                "book3", "1984"
            ));
    
            // Removing an existing book from the catalog
            libraryCatalog.remove("book1");
            System.out.println("Removed book1: " + libraryCatalog.get("book1")); // Output: "Removed book1: null"
        }
    }
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal