Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through List of Objects that contain a true Boolean field value using Java 8 Optional<T>, Stream

I have been advised NOT to use .anyMatch(Predicate.isEqual(true)) by my colleagues. Reason being, it's not Null-Safe. They suggested that I should use Optional<Boolean> instead.

I have a List of Accounts, I want to return a true Boolean value only if when an account has an active loan outstanding, otherwise false.

@Data
public class Account {
    private String accountNumber;
    @Getter(AccessLevel.NONE)
    private Boolean activeLoan;
    private String accountReference;
    private Double balance;
    private String status;

    public Boolean hasActiveLoan() {
        return activeLoan;
    }
}

In other words, only when hasActiveLoan() is equal to true.

Below is my proposed solution:

 Boolean checkActiveLoanRule(List<Account> accounts) {

         Optional<Boolean> loanAccountExists = Optional.of(accounts.stream()
                .map(Account::hasActiveLoanAccount)
                .anyMatch(Predicate.isEqual(true)));

         return loanAccountExists.equals(Optional.of(true));
     }

Can this be refactored to be improved somehow? Any alternative ideas?

& Most importantly, is such a solution thread-safe?

like image 598
S34N Avatar asked Sep 12 '26 13:09

S34N


2 Answers

Your colleagues are wrong. Predicate.isEqual() is null safe. You can verify by reading the documentation, running a test, or checking the source.

As for Stream.anyMatch(), that returns a primitive boolean, which can't be null to begin with.

like image 124
shmosel Avatar answered Sep 15 '26 02:09

shmosel


The proper way is

boolean checkActiveLoanRule(List<Account> requiredQueuesInput) {
    return requiredQueuesInput.stream().anyMatch(Account::hasActiveLoan);     
}

You can change the return type to Boolean which I would advise against but it is your choice.

If you are worried that isActiveLoanAccount returns null then you have a bigger problem. Methods should not ever return null but either always return a non-null actual value or Optional<Something>. That means that hasActiveLoan should take care of the null-check being:

public Boolean hasActiveLoan() { // I would prefer a boolean here
    return activeLoan == null ? false : activeLoan; // or Boolean.FALSE
}
like image 28
luk2302 Avatar answered Sep 15 '26 04:09

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!