I want to filter all the transfers for which the signedOn field is null. When I run the first piece of code it's clear which ones are null and which ones are not and they're logged correctly, but when I run the stream filter it returns an empty list and I can't seem to find what's the problem with it... signedOn is a Date field.
This works and logs all wether the entries are null or not:
for (Transfer transfer : route.getTransferCollection()) {
if (transfer.getSignedOn() == null) {
logInfo("This transfer is null");
} else if (transfer.getSignedOn() != null) {
logInfo("This transfer is not null");
}
}
This returns an empty list:
return route.getTransferCollection()
.stream()
.filter(transfer -> transfer.getSignedOn() == null)
.collect(Collectors.toList());
}
If the Stream is empty (and it doesn't matter if it's empty due to the source of the stream being empty, or due to all the elements of the stream being filtered out prior to the terminal operation), the output List will be empty too. Save this answer.
stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.
Collector. toList() will return an empty List for you.
Return Value : Stream empty() returns an empty sequential stream. Note : An empty stream might be useful to avoid null pointer exceptions while callings methods with stream parameters.
You can log your statements inside the filter
itself
return route.getTransferCollection()
.stream()
.filter(transfer -> {
boolean test = transfer.getSignedOn() == null;
if(test){
// log wathever
} else {
// log diff
}
return test
})
.collect(Collectors.toList());
You can use peek
to log inside streams btw, but using it in your case would require to test against null twice.
You can also use a different collector may be to get the ones that are null and the ones that are not (without filter
):
.collect(Collectors.partitioningBy(transfer -> transfer.getSignedOn() == null))
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