-1

Let's say I have a Java Stream that contains null values.

How do you remove them ?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Chris
  • 4,212
  • 5
  • 37
  • 52
  • 3
    You can't really remove them from a stream, but you can decide to ignore them… See your own answer for some ideas ;-) – deHaar Aug 12 '22 at 06:46
  • 2
    @deHaar - `filter` is *really* removing the nulls from the `Stream`. (It is not removing them from the *source* of the `Stream`, but you can't do that anyway.) – Stephen C Aug 12 '22 at 06:48
  • If you want evidence, see https://stackoverflow.com/questions/72819470. And https://stackoverflow.com/questions/63991118. And I could probably find more. The point is that this is a succinct question, where the others that I can find all require the reader to disentangle a bunch of context. – Stephen C Aug 12 '22 at 06:55
  • @StephenC OK, you are right, one can remove/ignore/filter values from the stream. The source stays untouched, that's what my first comment was supposed to say but used inappropriate terminology. – deHaar Aug 12 '22 at 07:24

1 Answers1

11

Here's a few ways I can think of:

stream.filter(x -> x != null).

stream.filter(Objects::nonNull)

Chris
  • 4,212
  • 5
  • 37
  • 52