英文:
How to return a different object based on Optional's null check on another different object in java?
问题
以下是您要求的翻译内容:
如何将此代码转换为使用 Optionals 的现代 Java 语法?
public String computeName(Person person) {
if(person != null) return person.getName();
return null;
}
我尝试了以下方式,但当然这是错误的,因为 orElse
将会返回一个 Person 对象实例,而不是 String 名称。为了使其工作,我认为我需要链接另一个 Optional。
public String getName(Person person) {
return Optional.ofNullable(person).orElse(person.getName());
}
我想要减少这段代码,并且使用现代的 Java 语法来使用 Optionals 让其工作。或者使用其他标准库也可以,比如 Apache Commons 或 Google Guava 等。
基本上,我希望在 person 对象本身不为 null 的情况下返回 person 的姓名。如果有必要,我的方法返回 null 而不是字符串,因为调用方总是使用 Apache Commons 的 StringUtils.isNotBlank
来检查(顺便提一下,该方法也会检查 null)。
英文:
How to convert this to modern Java syntax using Optionals?
public String computeName(Person person) {
if(person != null) return person.getName();
return null;
}
I tried this, but of course this is wrong because orElse will return an instance of Person object, not the String name. For this to work, I would need to chain another optional I think.
public String getName(Person person) {
return Optional.ofNullable(person).orElse(person.getName());
}
I want to reduce the code and make this work using modern java syntax using Optionals. Or any other standard library is also fine like ApaceUtils or Google-Guava etc.
Essentially, I want to return person's name if the person object itself is not null. I am fine if my method returns null instead of a string in some cases as well, since the caller always checks using Apache Commons StringUtils.isNotBlank(which also check for null by the way).
答案1
得分: 2
以下是翻译好的代码部分:
-
Incomplete conversion, keeping the signature unchanged:
public static String computeName(Person person) { return Optional.ofNullable(person).map(Person::getName).orElse(null); }
-
Full conversion:
public static Optional<String> computeName(Person person) { return Optional.ofNullable(person).map(Person::getName); }
英文:
> lang-java
> public static String computeName(Person person) {
> if(person != null) return person.getName();
> return null;
> }
>
There are 2 ways to convert the above code to "modern Java syntax using Optional
":
-
Incomplete conversion, keeping the signature unchanged:
public static String computeName(Person person) { return Optional.ofNullable(person).map(Person::getName).orElse(null); }
-
Full conversion:
public static Optional<String> computeName(Person person) { return Optional.ofNullable(person).map(Person::getName); }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论