Retrieve an object field from a list of items with one map-filter lambda expression

hammerfest :

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) {...
Eugene :

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

Guess you like

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