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?
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.
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
}
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