首页 > 解决方案 > 从可为空的列表创建 Java 8 流

问题描述

有没有办法检查java8中的null,如果list为null返回null,否则执行操作。

 public Builder withColors(List<String> colors) {
        this.colors= colors== null ? null :
                colors.stream()
                .filter(Objects::nonNull)
                .map(color-> Color.valueOf(color))
                .collect(Collectors.toList());

        return this;
    }

我看到有一个选项可以使用

Optional.ofNullable(list).map(List::stream) 

但这样我在 Color.valueOf(color) 上得到错误代码

谢谢

标签: javajava-8java-stream

解决方案


Optional.ofNullable(list).map(List::stream)会给你一个Optional<Stream<String>>,你不能打电话filter

您可以将整个Stream处理过程放在Optional's中map()

public Builder withColors(List<String> colors) {
    this.colors = Optional.ofNullable(colors).map(
        list -> list.stream()
                    .filter(Objects::nonNull)
                    .map(color-> Color.valueOf(color))
                    .collect(Collectors.toList()))
                    .orElse(null);
    return this;
}

推荐阅读