Optional.ofNullable(itemKey) 比 itemKey == null 有什么优势

What's the advantage of Optional.ofNullable(itemKey) over itemKey == null

我只是想知道我们什么时候需要选择可选而不是 if else 或嵌套 null 检查。举例来说,下面是否有任何优势,或者您认为可选的可能是一种矫枉过正

String.valueOf(Optional.ofNullable(itemKey).map(ItemKey::getId).orElse(null));

String.valueOf(itemKey == null ? null : itemKey.getId());

当我不得不选择给定对象的嵌套项目时,我总是热衷于使用 Optional.ofOptional.ofNullable,如下所示,

private String formatCurrency(String symbol, BigDecimal value) {
    return Optional.ofNullable(value)
            .map(BigDecimal::doubleValue)
            .map(Object::toString)
            .map(val -> symbol + val.replaceAll(REGEX_REMOVE_TRAILING_ZEROS, ""))
            .orElse("");
}

我能知道在代码的什么地方绝对不需要 Optional 吗?

如果你的代码中已经有itemKey,那么将其转化为Optional没有任何意义,只会让代码变得更复杂。但是,如果你想使用可选值,我认为这样做更合适:

public Optional<ItemKey> getItemKey() {
    if (...) {
        return Optional.of(new ItemKey());
    }
    return Optional.empty()
}

public void mainCode() {
    String id = getItemKey().map(ItemKey::getId).orElse(null);
}