空指针异常发生在Optional.ofNullable()内部。

huangapple go评论76阅读模式
英文:

Null pointer exception inside Optional.ofNullable()

问题

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

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

但是如果sampleSetnull,它会抛出NullPointerException异常。有人可以告诉我如何使用.map方法和Optional解决这个问题吗?

我知道一种传统的方法是事先检查可空性:

if (rule.getSampleSet() != null)

但我更想知道是否可以在一行中完成。

英文:

I am trying to convert a set to string inside Optional.OfNullable method like:

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

but if sampleSet is null it will give me a NullPointerException.
can anyone tell me how to resolve this issue using .map method with Optional?

I know one traditional way of doing it by checking nullability beforehand:

if(rule.getSampeSet != null)

but I am much interested in knowing if we can do it in one line.

答案1

得分: 8

代替在 ofNullable 内部调用 toString(),你可以使用 map 将可选项映射到它:

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

Instead of calling toString() inside the ofNullable, you could map the optional to it:

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

huangapple
  • 本文由 发表于 2020年4月9日 03:28:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/61108531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定