我有这个不安全的代码,可能会引发 nullPtr 异常:
Type t = objParam.getProject().getType();
如何使用 java 8 可选和 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 ???
最佳答案
Optional.map
的功能是它返回一个 Optional
,仅当原始变量也 isPresent
时该值才具有值。所以我怀疑你只是想要:
obj.map(Obj::getProject).map(Project::getType).map(Type::getName);
请注意,ifPresent
具有完全不同的目的:它允许消费者
仅在值存在时接受
值。所以对于类似的事情:
...map(Type::getName).ifPresent(System.out::println);
关于java - 如何从java8中的ifpresent返回进行Optional<T>空指针检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800691/