Meysam Zarei :
I have a list that contains some home numbers, and they have 'isPrimary' and 'number' properties.
"homeNumbers": [
{
"isPrimary": true,
"number": "9999999999"
},
{
"isPrimary": false,
"number": "9999999323"
}
]
Now, I want to write two conditions on the list to match ONLY one of them, I mean this list must have one primary number and its number mustn't be null.
I have written below code but it just checks whether there is any primary number or not, Now, I want to know how to expand it to check just one of them is primary.
private boolean isSetPrimaryHomeNumber(UpdateWorkerDto updateWorkerDto) {
return updateWorkerDto.getPhoneNumbers().getHomeNumbers().stream().anyMatch(
number -> Objects.requireNonNullElse(number.getIsPrimary(), false) && !number.getNumber().isEmpty());
}
Nicktar :
You could filter by primary numberst first and then filter those again for Non-Null numbers, then count and compare to 1 like this:
boolean isValid(List<HomeNumber> numbers) {
return numbers.stream()
.filter(HomeNumber::isPrimary)
.filter(n -> Objects.notNull(n.getNumber()))
.count() == 1;
}