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>)]