我有这个不安全的代码,可能会抛出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 ???
答案 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}}