gpt4 book ai didi

Java 8 可选类 : return value if nullable

转载 作者:行者123 更新时间:2023-11-29 09:51:48 24 4
gpt4 key购买 nike

我正在尝试将现有的代码片段转换为一些精美的 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;
}

到目前为止我的解决方案,如果参数为 null,则缺少处理。

public static Foo getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get)
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code));
}

最佳答案

你可以返回Optional<Foo>来自 getForCode(final Integer code)并让客户端处理返回的可选值。

public static Optional<Foo> getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get);
}

关于Java 8 可选类 : return value if nullable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49112837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com