1
I am new to Java8. In recent project I am trying Optional with map and flatmap to prevent NPE.

I tried map and flatmap both with Optional but when I am using flatMap the compiler is giving error.

public class Project {
    private ApplicationType applciationType;
}


@Getter
@Setter
public class ApplicationType {

    public String getDirectory() {      
        return "Inside my directory";
    }
}


public class Driver {

    public static void main(String[] args) {
        ApplicationType appType = new ApplicationType();
        Project project = new Project(appType);

         //When using map its running fine.
        Optional.ofNullable(project)
        .map(prjct-> prjct.getApplciationType())
        .map(appType1 -> appType1.getDirectory())
        .ifPresent(e -> System.out.println(e));

        //When using flatMap.. comiplation error.
        Optional.ofNullable(project)
        .map(prjct-> prjct.getApplciationType())
        .flatMap(appType1 -> appType1.getDirectory())
        .ifPresent(e -> System.out.println(e));

    }

}

Sorry if I am missing something basic here. Just trying to learn and implement java8 features in future projects.

compilation error I am getting -> [Cannot infer type argument(s) for flatMap(Function>)]

Naman
  • 27,789
  • 26
  • 218
  • 353
GAURAV PANT
  • 135
  • 4
  • 11
  • why are you trying to use `flatMap`? just use `.map(Project::getApplicationType).filter(Objects::nonNull)` – Adrian Jun 10 '19 at 06:43
  • Thanks for the comment Adrian. Kindly let me know in which scenario I have to use flatMap when working with Optionals? – GAURAV PANT Jun 10 '19 at 06:46

2 Answers2

2

Purpose of Optional.flatMap() is to unwrap Optional from function.

For example, if your getDirectory returns Optional<String>, then .map() call would give you Optional<Optional<String>>, but if you use flatMap() - it gives you just Optional<String>.

DDovzhenko
  • 1,295
  • 1
  • 15
  • 34
1

See the signature of flatMap:

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)

The Function is supposed to return an Optional, so in order to use it, you'll need to write:

Optional.ofNullable(project)
    .map(prjct-> prjct.getApplciationType())
    .flatMap(appType1 -> Optional.ofNullable(appType1.getDirectory()))
    .ifPresent(e -> System.out.println(e));

Of course, using map makes more sense in this example (as in your first snippet, which passes compilation).

Eran
  • 387,369
  • 54
  • 702
  • 768