Skip to content
Advertisement

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");
  }
  else{
    newObjs.add(...)
  }
}

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

Advertisement

Answer

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

List<Obj> newObjs = objects.stream().peek(x -> {
    if (x == null) logger.error("null object");
}).filter(Objects::nonNull).collect(Collectors.toList());

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement