I'm trying to convert an existing snippet of code to some fancy Java 8 one-liner.
private static final Map<Integer, Foo> FOO_MAP = ...
public static Foo getForCode(final Integer code) {
if (code == null) {
return null;
}
final Foo foo = FOO_MAP.get(code);
if (foo== null) {
throw new IllegalStateException("Unknown foo for code: " + code);
}
return foo;
}
My solution so far, which is lacking the handling if the param is null.
public static Foo getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get)
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code));
}
ifstatements. Your original code is clearly superior.Optionalinstance is not designed to perform distinct checks as the OP wants but it doesn't mean that it should not be used as type of return of the method.Optionalallows to convey that the return may contain nothing and it also preventsNullPointerException.nullif the input isnull, is questionable to begin with. The preferred behavior is “fail-fast” instead of letting the programmer trace backward through the program to find out, where the originalnullcame from. When you replaceOptional.ofNullable(code)withOptional.of(code)in your code, you already have the recommended behavior.