No value present 异常(Stream流异常)

2023-10-23 15:58:30 浏览数 (3)

使用stream流时,未考虑数据不存在,直接使用get(),则会出现 No value present 异常。

异常代码:

代码语言:javascript复制
ScreenPointInfo screenPoint = allPoints.stream()
              .filter(screenPointInfo -> screenPointInfo.getPointCode().equals(devicePointCode)
                      && screenPointInfo.getDataFrom().equals(new Integer(1)))
              .findFirst().get();

修正后代码(将.get()替换为.orElse()):

代码语言:javascript复制
ScreenPointInfo screenPoint = allPoints.stream()
              .filter(screenPointInfo -> screenPointInfo.getPointCode().equals(devicePointCode)
                      && screenPointInfo.getDataFrom().equals(new Integer(1)))
              .findFirst().orElse(null);

1 人点赞