Practical Examples: Maps and Pair Operations
You'll learn how to apply binary functional interfaces to solve common Map operations involving key-value pairs.
Why Binary Interfaces Are Perfect for Maps
Maps store key-value pairs, and binary functional interfaces naturally handle two inputs—exactly what you need when working with both a key and a value. This makes BiFunction, BiConsumer, and BiPredicate ideal tools for Map operations.
Real-World Map Operations
forEach with BiConsumer
The Map.forEach method accepts a BiConsumer<K, V> to process each entry:
Map<String, Integer> inventory = Map.of(
"apples", 10,
"oranges", 5,
"bananas", 8
);
// Print all entries
inventory.forEach((fruit, quantity) ->
System.out.println(fruit + ": " + quantity)
);
computeIfPresent with BiFunction
Update values conditionally using BiFunction<K, V, V>:
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 90);
// Add bonus points to Alice's score if she exists
scores.computeIfPresent("Alice", (name, score) -> score + 10);
// Alice now has 95
// Returns null if key doesn't exist
scores.computeIfPresent("Charlie", (name, score) -> score + 10);
// No change, Charlie wasn't in the map
replaceAll with BiFunction
Transform all values based on their keys:
Map<String, String> messages = new HashMap<>();
messages.put("user1", "hello");
messages.put("user2", "goodbye");
// Personalize all messages
messages.replaceAll((user, message) ->
user + " says: " + message
);
// user1 → "user1 says: hello"
The Pattern
Binary interfaces treat Map entries as pairs of related data—like processing orders with (customerId, amount) or settings with (configKey, configValue).
Key Takeaway: Binary functional interfaces (BiFunction, BiConsumer, BiPredicate) are the natural fit for Map operations, letting you elegantly process both keys and values together in methods like forEach, computeIfPresent, and replaceAll.