Java 8 流 – 避免空指针异常

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

Java 8 stream - avoid NPE

问题

我想从以下代码中获取数据:

MyObject.builder()
    .lastUpdated(tuple.getT2().isEmpty() ? null : tuple.getT2().get(0).getLastUpdated().toInstant())
    ...
    ...
    .build()

tuple.getT2().get(0).getLastUpdated() 可能为空...

我尝试过:

.lastUpdated(
    tuple.getT2().stream()
        .map(Optional::ofNullable)
        .findFirst()
        .flatMap(Function.identity())
        .map(metadata -> metadata.getLastUpdated().toInstant()) //NPE
        .orElse(null))

但是在这一行中我得到了 NPE:

.map(metadata -> metadata.getLastUpdated().toInstant())
英文:

I want to get the following data from:

MyObject.builder()
    .lastUpdated(tuple.getT2().isEmpty() ? null : tuple.getT2().get(0).getLastUpdated().toInstant())
...
...
.build()

tuple.getT2().get(0).getLastUpdated() can be null...

I tried:

.lastUpdated(
                        tuple.getT2().stream()
                            .map(Optional::ofNullable)
                            .findFirst()
                            .flatMap(Function.identity())
                            .map(metadata -> metadata.getLastUpdated().toInstant()) //NPE
                            .orElse(null))

but I get NPE in the line

.map(metadata -> metadata.getLastUpdated().toInstant())

答案1

得分: 6

以下是翻译的部分:

map lambda并不是一个魔法地方,其中NPEs不会发生。如果你有一个可能为空的东西,你需要进行映射以避免NPEs。用以下内容替换这个调用:

.map(metadata -> metadata.getLastUpdated().toInstant())

替换为:

.map(TypeOfMetadata::getLastUpdated)
.map(TypeOfGetLastUpdated::toInstant)

如果metadata.getLastUpdated()为空,这将使用orElse值。

英文:

The map lambda is not some magic place where NPEs do not happen. If you have a thing that could be null, you need to map to it to avoid NPEs. Replace this call:

.map(metadata -> metadata.getLastUpdated().toInstant())

with

.map(TypeOfMetadata::getLastUpdated)
.map(TypeOfGetLastUpdated::toInstant)

This will make it use the orElse value if metadata.getLastUpdated() is null.

huangapple
  • 本文由 发表于 2020年7月28日 18:37:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63132169.html
匿名

发表评论

匿名网友

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

确定