Optional.ofNullable() 内的空指针异常

Null pointer exception inside Optional.ofNullable()

我正在尝试在 Optional.OfNullable 方法中将集合转换为字符串,例如:

test.setAbc(Optional.ofNullable(rule.getSampleSet().toString()).orElse(null));

但是如果 sampleSetnull 它会给我一个 NullPointerException。 谁能告诉我如何使用 .map 方法和 Optional 来解决这个问题?

我知道一种通过预先检查可空性来执行此操作的传统方法:

if(rule.getSampeSet != null)

但我很想知道我们是否可以一行完成。

而不是在 ofNullable 中调用 toString(),您可以 map 它的可选值:

test.setAbc(Optional.ofNullable(rule.getSampleSet()).map(Object::toString).orElse(null));