javaintermediate
Java Map — Advanced Operations
Master Map operations: compute, merge, getOrDefault, multi-map, BiMap, and stream-based grouping.
javaPress ⌘/Ctrl + Shift + C to copy
import java.util.*;
import java.util.stream.Collectors;
public class MapOps {
public static void main(String[] args) {
// computeIfAbsent — lazy init
Map<String, List<String>> multiMap = new HashMap<>();
multiMap.computeIfAbsent("fruits", k -> new ArrayList<>()).add("apple");
multiMap.computeIfAbsent("fruits", k -> new ArrayList<>()).add("banana");
multiMap.computeIfAbsent("vegs", k -> new ArrayList<>()).add("carrot");
System.out.println(multiMap); // {fruits=[apple, banana], vegs=[carrot]}
// merge — combine values
Map<String, Integer> scores = new HashMap<>();
scores.merge("alice", 10, Integer::sum);
scores.merge("alice", 20, Integer::sum);
scores.merge("bob", 15, Integer::sum);
System.out.println(scores); // {alice=30, bob=15}
// compute — transform in-place
scores.compute("alice", (k, v) -> v == null ? 1 : v * 2);
// getOrDefault
int bobScore = scores.getOrDefault("charlie", 0);
// putIfAbsent — only set if missing
scores.putIfAbsent("alice", 999); // no-op, alice exists
// Iterate entries
scores.forEach((name, score) ->
System.out.printf("%s: %d%n", name, score));
// Stream groupingBy
record Product(String name, String category, double price) {}
var products = List.of(
new Product("iPhone", "Electronics", 999),
new Product("MacBook", "Electronics", 1999),
new Product("Shirt", "Clothing", 49),
new Product("Jeans", "Clothing", 79)
);
Map<String, DoubleSummaryStatistics> stats = products.stream()
.collect(Collectors.groupingBy(
Product::category,
Collectors.summarizingDouble(Product::price)
));
stats.forEach((cat, s) ->
System.out.printf("%s: avg=$%.0f, count=%d%n", cat, s.getAverage(), s.getCount()));
// Invert map (swap keys and values)
Map<String, Integer> original = Map.of("a", 1, "b", 2, "c", 3);
Map<Integer, String> inverted = original.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
// Unmodifiable copy
Map<String, Integer> frozen = Map.copyOf(scores);
}
}Use Cases
- Aggregation and grouping operations on data
- Multi-valued maps and frequency counters
- Configuration and lookup table management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javabeginner
HashMap Operations and Patterns
Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.
Best for: Counting word frequencies in text
#java#collections
javaintermediate
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#collections
javabeginner
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
#java#streams
javaadvanced
Concurrent Collections — Thread-Safe Maps
Use ConcurrentHashMap, CopyOnWriteArrayList, and BlockingQueue for thread-safe data structures.
Best for: Thread-safe caching in multi-threaded applications
#java#concurrency