Java 8的Optional,组合语句

huangapple go评论63阅读模式
英文:

Java 8 Optionals, Combining Statements

问题

我是新手,对Java 8的可选项不太熟悉,我想知道是否有一种方法可以将这两个语句合并成一个,同时保留可选项?

public List<String> getEmployeeStreetNames(Employee employee) {
    return Optional.ofNullable(employee)
        .map(Employee::getAddresses)
        .orElse(new ArrayList<>())
        .stream()
        .map(Address::getStreetName)
        .collect(Collectors.toList());
}

任何帮助都将不胜感激。

英文:

I'm new to Java 8 optionals and I'm wondering if there is a way to combine these two statements into one while retaining the optional?

public List&lt;String&gt; getEmployeeStreetNames(Employee employee){
     List&lt;Addresses&gt; addresses = Optional.ofNullable(employee)
     .map(Employee::getAddresses)
      .orElse(new ArrayList&lt;&gt;());

   return addresses.stream()
       .map(Address::getStreetName)
       .collect(Collectors.toList())
}

Any help is greatly appreciated.

答案1

得分: 3

避免在"maybe"管道步骤中创建新对象,比如orElse;即使参数未使用,您总是会产生创建参数的开销。更喜欢像Supplier<T>这样的签名,或者在这种情况下,Collections.emptyList()。(对于异常尤其重要;始终使用MyException::new() -> new MyException(foo)。)

在这种情况下,有几种处理管道的方式,可以是嵌套的或连续的。

return Optional.ofNullable(employee)
    .map(Employee::getAddresses)
    .map(a -> a.stream().map(Address::getStreetName).collect(toList()))
    .orElse(emptyList());

return Optional.ofNullable(employee)
    .map(Employee::getAddresses)
    .orElse(emptyList())
    .stream()
    .map(Address::getStreetName)
    .collect(toList());

我通常会选择嵌套版本,因为嵌套管道并不难理解。

英文:

First, avoid creating new objects in "maybe" pipeline steps like orElse; you always incur the overhead of creating the parameter even if it's unused. Prefer signatures like Supplier&lt;T&gt; or, in this case, Collections.emptyList(). (This is especially important for exceptions; always use MyException::new or () -&gt; new MyException(foo).)

In this case there are a couple of ways to handle the pipeline, either nested or consecutive.

return Optional.ofNullable(employee)
    .map(Employee::getAddresses)
    .map(a -&gt; a.stream().map(Address::getStreetName).collect(toList()))
    .orElse(emptyList());

return Optional.ofNullable(employee)
    .map(Employee::getAddresses)
    .orElse(emptyList())
    .stream()
    .map(Address::getStreetName)
    .collect(toList());

I'd generally go with the nested version, since the nested pipeline isn't at all difficult to understand.

huangapple
  • 本文由 发表于 2020年8月8日 06:40:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63309986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定