gpt4 book ai didi

java - 从可空列表创建 Java 8 流

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:28 28 4
gpt4 key购买 nike

有没有办法在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) 的错误代码

谢谢

最佳答案

Optional.ofNullable(list).map(List::stream)会给你一个Optional<Stream<String>> ,你不能称之为 filter上。

你可以把整个Stream Optional内部处理的 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;
}

关于java - 从可空列表创建 Java 8 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51008748/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com