Is there a shorter syntax to if/throw else/return in Java 8? java.util.Optional
provides a means to accomplish this in one statement, but it requires creating an Optional
instance with every call that has a non-null reference.
public static MyEnum fromString(String value) {
MyEnum result = enumMap.get(value);
if (result == null)
throw new IllegalArgumentException("Unsupported value: " + value);
return result;
}
public static MyEnum fromString(String value) {
return Optional.ofNullable(enumMap.get(value)).orElseThrow(
() -> new IllegalArgumentException("Unsupported value: " + value));
}
The impact of a temporary Optional
instance is negligible. Usually the JVM will detect its temporary nature and optimize away the instance. Even if the temporary instance creation is not optimized away, the impact of one single temporary object on the memory management is ridiculously low. See also GC overhead of Optional<T> in Java.
However, if the map is mutable, you can use the following trick:
public static MyEnum fromString(String value) {
return enumMap.computeIfAbsent(value, v -> {
throw new IllegalArgumentException("Unsupported value: " + v); });
}
Note that the Map
is not modified by this code but still must be mutable as an immutable map might throw an UnsupportedOperation
exception for the attempt to use computeIfAbsent
without ever checking whether the operation would really modify the map.
But in the end, there is nothing wrong with Optional
. But note that the code in your question is wrong. The lambda expression you pass to the method Optional.orElseThrow
is meant to supply the desired exception, not to throw it:
public static MyEnum fromString(String value) {
return Optional.ofNullable(enumMap.get(value)).orElseThrow(() ->
new IllegalArgumentException("Unsupported value: " + value) // just return it
);
}
If you are willing to live with NullPointerException
, you can do:
public static MyEnum fromString(String value) {
return requireNonNull(enumMap.get(value), () -> "Unsupported: " + value);
}
This assumes import static java.util.Objects.requireNonNull
Edit:
If you are really particular about what type of exception you throw, just implement your own static utility method:
static<T, X extends Throwable> T nonNullOrThrow(T val, Supplier<? extends X> exSupplier) throws X {
if (val != null) return val;
else throw exSupplier.get();
}
Then you'll be able to do
return nonNullOrThrow(enumMap.get(value), () -> new IllegalArgumentException("unsupported: " + k));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With