Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
frazman Avatar asked Mar 02 '23 03:03

frazman


2 Answers

I would suggest to move that logic into different method

public boolean filter(Object obj) {

  if(obj == null){
      logger.error("null object");
      return false;
    }
  return true;
}

And then just stream the list

objects.stream().filter(this::filter).collect(Collectors.toList());
like image 139
Deadpool Avatar answered Mar 04 '23 17:03

Deadpool


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.

like image 34
Sweeper Avatar answered Mar 04 '23 16:03

Sweeper