Java.Java8.What additional methods for working with associative arrays (maps) appeared in Java 8?

Java 8 brought some powerful new methods to Map that made working with associative arrays (maps) much cleaner, safer, and more expressive. 💡 Let’s go over the most useful ones:


✅ New Map Methods in Java 8

MethodPurpose
getOrDefault()Returns value if present, or default value if key is missing
putIfAbsent()Puts a value only if the key is not already associated with one
compute(), computeIfAbsent(), computeIfPresent()Dynamically compute values
merge()Merges values in a map using a remapping function
forEach()Iterates over entries using a BiConsumer
replace()Replaces value for a key (optional conditional version)
replaceAll()Replaces all values using a BiFunction
remove(key, value)Removes entry only if key maps to that exact value

🔍 Examples of Each

🔹 getOrDefault()

map.getOrDefault("apple", 0); // returns 0 if "apple" is not found

🔹 putIfAbsent()

map.putIfAbsent("apple", 10); // only puts if key not present

🔹 computeIfAbsent()

map.computeIfAbsent("banana", k -> 42); // adds banana=42 if not present

Great for lazy loading or initializing maps.

🔹 computeIfPresent()

map.computeIfPresent("apple", (k, v) -> v + 1); // only updates if present

🔹 compute()

map.compute("apple", (k, v) -> (v == null) ? 1 : v + 1);

Use when you don’t care whether the key exists or not.

🔹 merge()

map.merge("apple", 1, Integer::sum); // adds or updates value by summing

Very useful for counting frequency of items!

🔹 forEach()

map.forEach((key, value) -> System.out.println(key + ": " + value));

🔹 replace() and replaceAll()

map.replace("apple", 5); // replaces value
map.replaceAll((k, v) -> v * 2); // doubles all values

🔹 remove(key, value)

map.remove("apple", 10); // only removes if key maps to 10

🧠 Use Cases

  • Building caches or counters with computeIfAbsent / merge
  • Writing cleaner iteration logic with forEach
  • Simplifying default value logic with getOrDefault
  • Avoiding race conditions in concurrent use cases
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.