Mapmap = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); Integer value = map.computeIfAbsent("orange", k -> 3); System.out.println(value); // Output: 3 System.out.println(map); // Output: {banana=2, apple=1, orange=3}
MapIn this example, we have a `Map` of `String` keys and `List` of `Integer` values. Initially, the map contains pairs for `even` and `odd` keys. We call `computeIfAbsent()` with the key `prime` and specify a function that returns a new `ArrayList`. This creates a new key-value pair for `prime` in the map with an empty `ArrayList` as the value. We then call `add()` method to add some `Integer` values to the `ArrayList`, which is retrieved from the map using `get()` method. The `computeIfAbsent()` method is part of Java's standard library and is available in the `java.util` package.> map = new HashMap<>(); map.put("even", Arrays.asList(2, 4, 6)); map.put("odd", Arrays.asList(1, 3, 5)); map.computeIfAbsent("prime", k -> new ArrayList ()); map.get("prime").add(2); map.get("prime").add(3); map.get("prime").add(5); System.out.println(map); // Output: {prime=[2, 3, 5], even=[2, 4, 6], odd=[1, 3, 5]}