英文:
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<String> getEmployeeStreetNames(Employee employee){
List<Addresses> addresses = Optional.ofNullable(employee)
.map(Employee::getAddresses)
.orElse(new ArrayList<>());
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<T>
or, in this case, Collections.emptyList()
. (This is especially important for exceptions; always use MyException::new
or () -> 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 -> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论