Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream Filter returning an empty list always [duplicate]

Tags:

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());
}
like image 410
brightpants Avatar asked Dec 10 '17 17:12

brightpants


People also ask

Does stream work on empty list?

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.

Does stream filter modify the original list?

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.

Does collectors toList return empty list?

Collector. toList() will return an empty List for you.

What happens if stream is empty?

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.


1 Answers

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))
like image 110
Eugene Avatar answered Oct 15 '22 11:10

Eugene