Append /src to an Optional path My method getProjectDir() will return an Optional which contains the path to the project directory, or an empty container:

Optional&lt;Path&gt; getProjectDir() { ... }


I have another method, getSrcDir() which depends on getProjectDir():

Optional&lt;Path&gt; getSrcDir() {
    Optional&lt;Path&gt; projectDir = getProjectDir();
    if (projectDir.isPresent()) {
        return Optional.of(projectDir.get().resolve("src"));
    }

    return Optional.empty();        
}


Everything works, but I feel the if statement is clunky. Is there any single statement which says "If the project dir exists, append "/src" to it, else return an empty optional. Please let me know if and how it can be done.
Sure there is! You're looking for Optional.map


  If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.


Optional&lt;Path&gt; getSrcDir() {
    return getProjectDir().map(p -&gt; p.resolve("src"));
}