Q:

Java Optional usage for multi-map

Continent is a composite Object. Structure is :
Continent
--Country
----State
------Town

so in this notation:
town= Optional.of(continent)
            .map(Continent::getCountry)
            .map(Country::getState)
            .map(State::getTown)
            .orElse(null);

this works fine, but when I try to write a general mapper,
  public static <T, R> T getFromMapping(R source,
                                      T defaultValue,
                                      Function<?,?>... functions) {
      Optional sourceWrapper = Optional.ofNullable(source);
      for (Function function : functions) {
         sourceWrapper.map(function);
      }
    return (T) sourceWrapper.orElse(defaultValue);
  }

and invoke it by 
 portfolio = getFromMapping(continent, null,
            ((Function<Continent, Country>) Continent::getCountry)
            ((Function<Country, State>) Country::getState),
            ((Function<State, Town>) State::getTown));

it compile just fine but don't work. The mapper jump to second step to and said Continent could not cast to country, why? there supposed to be no cast while doing mapping, how to fix it?

A:

Optional#map does not modify itself, but returns a new Optional instead, so sourceWrapper still contains your continent. You should reassign the variable in the for loop:
sourceWrapper = sourceWrapper.map(function);

