Skip to content

How to filter and log null objects in Java 8 streams

I am trying to wrap my head around java8 streams and was wondering if someone can help me with it.

In old java,

List<Obj> newObjs = ArrayList<Obj>();
for (Obj obj : objects){
  if(obj == null){
     logger.error("null object");

Basically, I want to filter null objects and also log it. What’s a good way to do this in java 8?



You can use peek and put an if statement inside it:

List<Obj> newObjs = -> {
    if (x == null) logger.error("null object");

But this kind of loses the conciseness of the streams, so personally I would still use a plain old for loop for something simple like “filtering nulls and collecting to a list”.

Keep in mind that Streams do not replace for loops. Don’t use streams just because it’s new and shiny.

9 People found this is helpful