Introduction to HashMap Operations in Java

Greetings, fellow Java enthusiast! As we embark on our Java programming journey today, we will get up close and personal with a mighty helpful companion—HashMap. Whether organizing a cookbook, tallying votes, or tracking inventory, HashMap comes to the rescue, providing a way to handle pairs of data efficiently. Let's explore how HashMap can transform complex tasks into straightforward ones through practical examples.

Problem 1: Word Counter

Consider this: you have an extensive text — perhaps a short story or a section of a report — and want to analyze word usage. How many times does each word appear? This isn't just about curiosity; such a tool benefits writers aiming for diverse vocabulary.

Visualize yourself tasked with developing a feature for a text editor that gives feedback on word usage. A writer could use this feature to refine their work, ensuring they use only certain words.

Problem 1: Naive Approach

Consider iterating over the text word by word, keeping track of each instance in a list. This approach might work for a short sentence, but imagine scaling it up to an entire book! It becomes inefficient as you repeatedly wade through a growing list for each word you encounter.

Problem 1: Efficient Approach

This is where HashMap shines like a knight in shining armor. With its getOrDefault function, HashMap allows for swift updates. Instead of a laborious search for each word, a HashMap can check and update the count in a constant time — a massive time-saver!

Problem 1: Build Solution

Let's break down the code step by step:

  1. We create a HashMap called wordCount to store words and their frequencies.
  2. using the split method around each space, we split the text into words.
  3. Then, for each word, we update the HashMap using the getOrDefault method, which fetches the current count and adds one. If the key is not in the HashMap, it creates the key and assigns it a value of 0.

Here's how our Java crusader does it:

import java.util.HashMap;

class Solution {
    public static void main(String[] args) {
        String text = "Java Java Java";
        HashMap<String, Integer> wordCount = new HashMap<>();
        String[] words = text.split(" ");
        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
        System.out.println(wordCount);
    }
}

Take the sentence "Java Java Java" for example. Our function would create a HashMap with a single entry: {"Java", 3}. Simple and elegant!

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