Introduction to HashMaps in Java for Counting Occurrences

Topic Overview

In this lesson, we will explore the concept and practical application of HashMaps in Java. HashMaps are a powerful and efficient data structure used for storing key-value pairs. You will learn how to utilize HashMap to count the frequency of elements in a collection, understand the underlying mechanics, and analyze the time and space efficiency of this approach. This lesson includes a step-by-step demonstration with detailed code examples and a discussion on the practical applications of using HashMaps for counting occurrences in various contexts.

Understanding the Problem

We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses a HashMap.

For a quick illustration, consider this list of colors:

import java.util.ArrayList;

class Solution {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("red");
        colors.add("blue");
        colors.add("red");
        colors.add("green");
        colors.add("blue");
        colors.add("blue");
    }
}

If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ HashMaps for a more efficient counting process.

Introducing HashMaps

Simple yet powerful, HashMaps allow us to store and retrieve data using keys. The unique colors in our list act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors list using Java's HashMap:

import java.util.HashMap;
import java.util.ArrayList;

class Solution {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("red");
        colors.add("blue");
        colors.add("red");
        colors.add("green");
        colors.add("blue");
        colors.add("blue");

        HashMap<String, Integer> colorMap = new HashMap<>();

        // Start the loop to iterate over each color
        for (String color : colors) {

            // If the color is present in our HashMap, increment its value by 1
            if (colorMap.containsKey(color)) {
                colorMap.put(color, colorMap.get(color) + 1);
            } else {
                // If the color isn't present, it means we're encountering this color in our list for the first time.
                // In this case, we add it to our HashMap and set its value to 1
                colorMap.put(color, 1);
            }
        }

        // Print our HashMap with counts
        for (String key : colorMap.keySet()) {
            System.out.println(key + ": " + colorMap.get(key));
        }
    }
}

When the above code executes, it displays the counts for each color:

red: 2
green: 1
blue: 3
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