We have a List of SomeType items from which we would like to retrieve a particular item, perform a check on that item (filter), and if the criteria is fulfilled, then retrieve a particular String type field from the item (map), all in one expression
The concerned method interfaces are as follows. All is going fine until the last step, where we would like to map the filter result Optional<SomeType>
into Optional<String>
. Unfortunately we are not able to nail the syntax expected by the map call
public Optional<String> transform(final List<SomeType> aList)
return getAnItemFromTheList(aList)
.filter(someFilterClass::anItemFulfillsCriteria)
.map(???use getAStringTypeFieldFromTheItem() here???);
private Optional<SomeType> getAnItemFromTheList(final List<SomeType> aList) {...
public boolean anItemFulfillsCriteria(final SomeType anItem) {... //in a separate class of filter methods
private Optional<String> getAStringTypeFieldFromTheItem(final SomeType anItem) {...
Well if I understood it correctly that getAStringTypeFieldFromTheItem
will return an Optional<String>
, thus you will end up with Optional<Optional<String>>
after the map
; thus just use flatMap
instead of map
to get that Optional<String>
as a result