0

I've been continuously coming across this need of HashMap method that help me to throw an error if the key is not found.

While it has the method to computeIfAbsent, I thought I will try to convert it to throw an exception if the key is absent. Here's the signature:

computeIfAbsent (Key , Function<? super K, ? extends V>)

However I'm unable to understand how java compiler behaves for below different approach.

public void testComputeIfAbsentWithLambda() {
        Map<String, String> keyVal = new HashMap<>();
        keyVal.computeIfAbsent("Hello", (k) -> "World!"); // works
        keyVal.computeIfAbsent("Hello", (k) -> throw new RuntimeException()); // doesn't compile
        keyVal.computeIfAbsent("Hello", (k) -> RuntimeException::new); // doesn't compile
        keyVal.computeIfAbsent("Hello", RuntimeException::new); // doesn't compile
        keyVal.computeIfAbsent("Hello", (k) -> { throw new RuntimeException(); } ); // works
    }

All I understand is the second argument must be a function that can accept the Key and return the value of type V. But not sure what is the difference between (k) -> throw new RuntimeException() and (k) -> { throw new RuntimeException(); }

Ketan Dhamasana
  • 61
  • 1
  • 1
  • 7
  • 1
    Note that `computeIfAbsent` requires a *mutable* map, even if the function never completes with a value. Hence, the idiomatic solution for throwing when a key is absent, still is `if(!keyVal.containsKey("Hello")) throw new RuntimeException();` This works with all maps. – Holger Oct 21 '22 at 09:32

0 Answers0