从可为空的列表创建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)上得到错误代码


谢谢


慕莱坞森
浏览 172回答 2
2回答

梵蒂冈之花

Optional.ofNullable(list).map(List::stream)会给您一个Optional<Stream<String>>,您无法调用filter。您可以将整个Stream处理放入Optional的中map():public Builder withColors(List<String> colors) {&nbsp; &nbsp; this.colors = Optional.ofNullable(colors).map(&nbsp; &nbsp; &nbsp; &nbsp; list -> list.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(Objects::nonNull)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(color-> Color.valueOf(color))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElse(null);&nbsp; &nbsp; return this;}

四季花海

您可能需要重新考虑几件事。首先可能要传递aSet<String> colors而不是aList会更有意义,因为似乎这Color是一个枚举。然后,可能会更有意义核对equalsIgnoreCase,这样red或RED会仍然产生一个枚举实例。另外if statement,检查可能为空的输入可能更清晰。以及最后一个相反方向的流-从这enum将更有意义(还避免了空检查),我只是为了简单起见没有实施上述建议。public Builder withColors(List<String> colors) {&nbsp; &nbsp; if(colors == null){&nbsp; &nbsp; &nbsp; &nbsp; this.colors = Collection.emptyList();&nbsp; &nbsp; }&nbsp; &nbsp; this.colors = EnumSet.allOf(Color.class)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(x -> colors.stream().anyMatch(y -> x.toString().equals(y)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());&nbsp; &nbsp; return this;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java