How has Map changed in recent Java versions?

In recent Java versions, particularly from Java 8 onwards, the Map interface has introduced several enhancements that improve its functionality and ease of use. Most notably, the addition of new methods such as forEach, computeIfAbsent, and merge has made it more versatile in handling entries directly.

Java Map, Java 8 features, Map enhancements, computeIfAbsent, forEach, merge


        // Example of using new Map methods
        import java.util.HashMap;
        import java.util.Map;

        public class MapExample {
            public static void main(String[] args) {
                Map map = new HashMap<>();

                // Adding entries using computeIfAbsent
                map.computeIfAbsent("apple", key -> 0);
                map.computeIfAbsent("banana", key -> 0);

                // Merging values
                map.merge("apple", 1, Integer::sum);
                map.merge("banana", 2, Integer::sum);

                // ForEach to print entries
                map.forEach((key, value) -> System.out.println(key + ": " + value));
            }
        }
    

Java Map Java 8 features Map enhancements computeIfAbsent forEach merge