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.
Can this be accomplished in a single statement?
public static MyEnum fromString(String value) {
MyEnum result = enumMap.get(value);
if (result == null)
throw new IllegalArgumentException("Unsupported value: " + value);
return result;
}
Optional Example (bad, requires Optional instance every time)
public static MyEnum fromString(String value) {
return Optional.ofNullable(enumMap.get(value)).orElseThrow(
() -> new IllegalArgumentException("Unsupported value: " + value));
}