Reputation:
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.
Upvotes: 3
Views: 77
Reputation: 77187
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.
Upvotes: 3