我试图将一组转换为Optional.OfNullable方法内的字符串,例如:
test.setAbc(Optional.ofNullable(rule.getSampleSet().toString()).orElse(null));
但是如果sampleSet
可以的null
话NullPointerException
。谁能告诉我如何使用.map
方法解决此问题Optional
?
我知道一种通过预先检查可空性的传统方式:
if(rule.getSampeSet != null)
但是我很想知道我们能否一站式完成。
而不是调用的toString()
内部ofNullable
,你可以map
选购到它:
test.setAbc(Optional.ofNullable(rule.getSampleSet()).map(Object::toString).orElse(null));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句