为了账号安全,请及时绑定邮箱和手机立即绑定

从可为空的列表创建Java 8流

从可为空的列表创建Java 8流

慕莱坞森 2021-04-13 17:10:31
有没有一种方法可以检查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)上得到错误代码谢谢
查看完整描述

2 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

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;

}


查看完整回答
反对 回复 2021-04-21
?
四季花海

TA贡献1811条经验 获得超5个赞

您可能需要重新考虑几件事。


首先可能要传递aSet<String> colors而不是aList会更有意义,因为似乎这Color是一个枚举。然后,可能会更有意义核对equalsIgnoreCase,这样red或RED会仍然产生一个枚举实例。另外if statement,检查可能为空的输入可能更清晰。以及最后一个相反方向的流-从这enum将更有意义(还避免了空检查),我只是为了简单起见没有实施上述建议。


public Builder withColors(List<String> colors) {

    if(colors == null){

        this.colors = Collection.emptyList();

    }


    this.colors = EnumSet.allOf(Color.class)

            .stream()

            .filter(x -> colors.stream().anyMatch(y -> x.toString().equals(y)))

            .collect(Collectors.toList());

    return this;

}


查看完整回答
反对 回复 2021-04-21
  • 2 回答
  • 0 关注
  • 171 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信