如何在Java 8中过滤包含空引用的元素

huangapple go评论67阅读模式
英文:

How to filter elements which contains null references in java 8

问题

目前我正在努力理解Java 8。

我有这段流操作代码

List<MyObject> parsedEvents = events.stream()
    .filter(Objects::nonNull)
    .filter(e -> e.foo() != null && e.bar() != null && e.baz() != null)
    .map(
         e -> MyObject.builder()
            .setFoo(e.foo())
            .setBar(e.bar())
            .setBaz(e.baz())
            .build()
    )
    .collect(Collectors.toList());

但是,有时候 e.foo() 可能为null,或者 e.bar() 可能为null,或者 e.baz() 可能为null。

因此,我想只筛选那些其中任何一个方法将返回null的事件。

在Java 8中有什么简洁的方法可以实现这个?

英文:

So currently I am trying to wrap my head around java 8.

I have this stream manipulation

    List&lt;MyObject&gt; parsedEvents = events.stream()
.filter(Objects::nonNull)
    .map(
         e -&gt; MyObject.builder()
.setFoo(e.foo())
.setBar(e.bar())
.setBaz(e.baz())
.build()
    ).collect(Collectors.toList());

But, sometimes e.foo() can be Null or e.bar() can be null or e.baz() can be null.

So, I want to just filter those events where any of those methods will return a null.

What's a clean way to do that in java 8.

答案1

得分: 1

试一下这个。

List<MyObject> parsedEvents = events.stream()
    .filter(Objects::nonNull)
    .filter(e -> Stream.of(e.foo(), e.bar(), e.baz())
        .allMatch(Objects::nonNull))
    .map(
        e -> MyObject.builder()
            .setFoo(e.foo())
            .setBar(e.bar())
            .setBaz(e.baz())
            .build())
    .collect(Collectors.toList());
英文:

Try this.

List&lt;MyObject&gt; parsedEvents = events.stream()
    .filter(Objects::nonNull)
    .filter(e -&gt; Stream.of(e.foo(), e.bar(), e.baz())
        .allMatch(Objects::nonNull))
    .map(
        e -&gt; MyObject.builder()
            .setFoo(e.foo())
            .setBar(e.bar())
            .setBaz(e.baz())
            .build())
    .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月28日 09:06:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64094704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定