14

When using a Java Stream, sometimes null values can occur after mapping. Currently when these values need to be omitted, I use:

.stream()
.<other operations...>
.filter(element -> element != null)
.<other operations...>

For a more functional style a tiny helper method is quickly written:

public static <T> boolean nonNull(T entity) {
    return entity != null;
}

So that you can use a method reference instead:

.stream()
.<other operations...>
.filter(Elements::nonNull)
.<other operations...>

I could not find such a jdk method, even though I would suspect they have included one. Is there a different approach here? Or did they omit this for a reason?

Boris van Katwijk
  • 2,998
  • 4
  • 17
  • 32
  • 11
    What's wrong with `e -> e != null`? – user253751 Mar 02 '16 at 07:55
  • 3
    Nothing in itself, but I prefer a method reference when this situation occurs in a pipeline using only method references. It felt like a combo breaker. – Boris van Katwijk Mar 02 '16 at 08:02
  • 1
    Related: [Is there any difference between Objects::nonNull and x -> x != null?](https://stackoverflow.com/questions/25435056/is-there-any-difference-between-objectsnonnull-and-x-x-null) – Jeffrey Bosboom Mar 02 '16 at 08:14
  • 1
    As a side note, the type parameter `` is obsolete for your `nonNull` method. It doesn’t change the fact that you can pass any object to it, so you can simply declare the parameter as `Object`. – Holger Mar 02 '16 at 09:12
  • @Holger I think you mean "redundant" not "obsolete" but very good point! – Mateusz Dymczyk Mar 02 '16 at 11:04
  • 1
    @Mateusz Dymczyk: that depends on whether it had a purpose in an older version of the code which I can’t decide, but yes, “redundant” is likely the better word. – Holger Mar 02 '16 at 11:35
  • @Holger It was a leftover of stripping an existing utility stream map method which used T in its return type – Boris van Katwijk Mar 02 '16 at 11:59
  • I guess Holger was right then :-) – Mateusz Dymczyk Mar 02 '16 at 13:30

2 Answers2

38

You can use Objects::nonNull from the Java8 SDK:

.stream()
.<other operations...>
.filter(Objects::nonNull)
.<other operations...>
Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
3

You can use the Objects::nonNull

Returns true if the provided reference is non-null otherwise returns false.

.stream()
.<other operations...>
.filter(Objects::nonNull)
.<other operations...>
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331