HashMap Operations and Patterns
Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.
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.
Java Map — Advanced Operations
Master Map operations: compute, merge, getOrDefault, multi-map, BiMap, and stream-based grouping.
Best for: Aggregation and grouping operations on data
MultiMap and BiMap Implementations
Implement MultiMap and BiMap data structures for one-to-many and bidirectional key-value mappings.
Best for: Tag/category systems with multiple values per key
Java Streams — Filter, Map, Collect
Process collections with Java Streams: filter, map, flatMap, reduce, and collect to lists or maps.
Best for: Transforming and filtering collections
Concurrent Collections — Thread-Safe Maps
Use ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue for thread-safe data structures.
Best for: Thread-safe caching in multi-threaded applications