gpt4 book ai didi

java - 从 Optional 返回值

转载 作者:行者123 更新时间:2023-11-29 04:57:58 25 4
gpt4 key购买 nike

<分区>

如何返回 String来自 Optional<String> 的值使用 ifPresent并避免 NullPointerException

例子:

public String longestName() {
Optional<String> longName = someList.stream().reduce((name1, name2) -> name1.length() > name2.length() ? name1 : name2);

// If I do not want to use following
// return longName.isPresent() ? longName.get() : "not present";

// Can I achieve this using longName.ifPresent or longName.orElse("not present");
}

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