I'm trying to get used to using lambda expressions, but I frequently get caught up against something basic like this:
public List<Location> findAllAccessByUser(User user) {
return listDao.getAccessList(user).stream()
.filter(list -> findBySubOrgId(list.getOwnerOrg().getId()).isPresent())
.map(list -> findBySubOrgId(list.getOwnerOrg().getId()).get())
.collect(Collectors.toList());
}
This method
- Gets a list of AccessList objects,
- reads the subOrgId property from each object
- uses the findBySubOrgId() method to return an (Optional) Location object.
- Collect the objects into a list of Location objects.
Since the findBySubOrgId() returns an Optional which may not be present, I figure I need to filter it so the return List doesn't contain any empty elements. But then I have the repeat call to the same method, which seems wasteful.
Ordinarily I'd assign it to a variable and reuse that, but I can't find a reference to how to do this with lambdas -- or if it's even necessary.
Alternately I could put a conditional in the map() expression instead, but again I'm not sure how to do this and be sure to remove nulls.
As written it works exactly as I expect, but I always try to optimize my code, and it never hurts to learn the right way to do things. What is the "correct" way to rewrite this? Or is it fine as is?
mapto theOptionalfirst, thenfilterout those that are not present, thenmapto their values. (Or useorElse(null)andfilteroutnullvalues to skip amapstep.)