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?
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With