I am stuck to this method because of the if else condition says that
Condition usersInSales && usersInPayments is always false
Condition usersInSales && usersInLoans is always false
Condition usersInPayments && usersInLoans is always false
I tried different condition combinations and added the false values to try resolve it but it didn’t help. Please can I have some help? Thanks in advance
private List<UserResource> usersFilteredByDepartment(List<UserResource> users, boolean usersInSales, boolean usersInPayments, boolean usersInLoans) { if (usersInSales) { return getUsersInSales(users); } else if (usersInPayments) { return getUsersInPayments(users); } else if (usersInLoans) { return getUsersInLoans(users); } else if (usersInSales && usersInPayments) { return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList()); } else if (usersInSales && usersInLoans) { return Stream.concat(getUsersInSales(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList()); } else if (usersInPayments && usersInLoans) { return Stream.concat(getUsersInPayments(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList()); } else return users; }
Advertisement
Answer
You have two solutions.
Reorder your conditions, as others have shown. In your code by time you hit the
&&
statements you have already dealt with the cases when one half is true. The&&
(two clauses) is more restrictive than a single clause.Alternatively, put the double clauses inside the previous ifs.
if (usersInSales) { return getUsersInSales(users); } else if (usersInPayments) { return getUsersInPayments(users); } else if (usersInLoans) { return getUsersInLoans(users); } else if (usersInSales && usersInPayments) { return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList()); } else if (usersInSales && usersInLoans) {...
becomes
if (usersInSales) { if (usersInPayments) { // Nested if is like && operator. return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList()); } else { return getUsersInSales(users); } } else if (usersInPayments) { ...
This is a little more efficient and I think generally preferable.