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(); }