我正在尝试将现有的代码片段转换为某些花哨的Java 8单行代码。
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;
}
到目前为止我的解决方案,如果param为null,则缺少处理。
public static Foo getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get)
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code));
}
答案 0 :(得分:4)
在不改变原始功能的行为的情况下,我不认为Optional
会在这里购买任何东西,除非有机会在其方法和lambda中埋藏一些复杂的条件。如果你要使用if语句和布尔表达式来最小化条件表达式,那么你最终得到这个:
Foo getForCode(Integer code) {
Foo foo = null;
if (code == null || (foo = FOO_MAP.get(code)) != null) {
return foo;
} else {
throw new IllegalStateException("Unknown foo for code: " + code);
}
}
在我看来,这比使用Optional
的任何解决方案更具可读性,尽管它仍然相当模糊。
如果您愿意更改函数的语义并返回Optional
,那么suggestion from Roshane Perera似乎是一种合理的方法(+1)。
答案 1 :(得分:3)
您可以从Optional<Foo>
返回getForCode(final Integer code)
并让客户端处理返回的可选值。
public static Optional<Foo> getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get);
}
答案 2 :(得分:2)
它不是很易读,但你可以:
Foo result = Optional.ofNullable(code)
.map(x -> Optional.ofNullable(FOO_MAP.get(x))
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code)))
.orElse(null);
答案 3 :(得分:1)
你可以先单独处理它 尝试在单个语句中混合两种情况可能会降低其可读性。
请注意,实际上您可能不需要使用Optional
Optional
对返回类型更有意义。在您的实际代码中,您将继续返回null
值。
以下是Optional
的用法,您可以在其中返回Optional
来处理返回的Foo
和不返回的Foo
两种情况:
public static Optional<Foo> getForCode(final Integer code) {
if (code == null)
return Optional.empty();
Optional<Foo> optional = Optional.ofNullable(map.get(code));
if (!optional.isPresent()) {
throw new IllegalStateException("Unknown foo for code: " + code);
}
return optional;
}