Java Optional orElse

Matley :

How to call orElse when in one of the map steps I get empty List?

MyObj myObj = new MyObj();
myObj.setAaa("aaa");
myObj.setBbb("bbb");
List<MyObj> myObjects = Arrays.asList(myObj);

Optional<List<MyObj>> opt = Optional.ofNullable(myObjects);

List<MyObj> result = opt
   //   .filter(el -> !returnEmptyList().isEmpty(el))
        .map(el -> returnEmptyList(el))
        .map(...)
        .map(...)
        .orElse(myObjects);

How to make sure that I'll reach orElse when in my map step the result is an empty List?

Approach with my filter step works but I don't want to call returnEmptyList() twice.

Naman :

If the map operation can return an empty list, you could place a filter before orElse as:

.map() // this can return an empty list
.filter(l -> !l.isEmpty()) 
.orElse(<return some default value>); 

// if the list is empty, it would evaluate to Optional.empty() and return via orElse 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76909&siteId=1