如何从java8中的ifpresent返回Optional <t>空指针检查?</t>

时间:2015-03-01 23:47:05

标签: java nullpointerexception optional

我有这个不安全的代码,可能会抛出nullPtr异常:

Type t = objParam.getProject().getType();

如何使用java 8 optional和ifpresent()安全地返回最少量的代码(一行代码)?

// How can I modify this  to return from the ifPresent()...or a better way in 
// java8?  how can I just return a string from the ifPresent() method?
// instead of on a separate if(...isPresent) <make the assignment>?
//
Optional<Obj> obj = Optional.ofNullable(objParam);
Optional<String> typeName = obj
.map(Project::getProject)
.map(Type::getType).ifPresent().getName(); // ??? how to get the type name ???

1 个答案:

答案 0 :(得分:4)

Optional.map的功能是返回Optional,如果原始变量isPresent,则只返回值。所以我怀疑你只是想要:

obj.map(Obj::getProject).map(Project::getType).map(Type::getName);

请注意,ifPresent的目的完全不同:仅当{1}} Consumer值存在时,才允许accept...map(Type::getName).ifPresent(System.out::println); 。对于类似的事情:

{{1}}