javabeginner

HashMap Operations and Patterns

Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.

java
import java.util.*;

public class HashMapOps {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();

        // Basic operations
        scores.put("Alice", 95);
        scores.put("Bob", 87);
        scores.putIfAbsent("Charlie", 92);

        // Get with default
        int score = scores.getOrDefault("Unknown", 0);

        // Merge — add to existing value
        scores.merge("Alice", 5, Integer::sum); // Alice = 100

        // Compute — transform value
        scores.compute("Bob", (k, v) -> v == null ? 0 : v + 10);

        // Iteration
        scores.forEach((name, s) ->
            System.out.printf("%s: %d%n", name, s));

        // Word frequency counter
        String[] words = {"hello", "world", "hello", "java"};
        Map<String, Integer> freq = new HashMap<>();
        for (String w : words) {
            freq.merge(w, 1, Integer::sum);
        }
        System.out.println(freq); // {hello=2, world=1, java=1}

        // Sorted by value
        scores.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
            .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
    }
}

Use Cases

  • Counting word frequencies in text
  • Caching and lookup tables
  • Aggregating data by key

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.