Search code examples
javaconditional-statementsmultiple-conditions

Java conditions execution in sequence


Is there a better way writing this logic.requirement is to apply sequence of conditions in the specific order. It’s a fall through conditional logic, assume it’s like a funnel. It has to go and execute the next rule or condition if the previous one doesn’t yield any result. I tried switch, but that doesn’t seem to be a proper solution as well.

private List<String> filteredData(){

List<String> filteredList = new ArrayList();

filteredList.addAll(method1())
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method2())
}
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method3())
}
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method4())
}
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method5())
}
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method6())
}
if(CollectionUtils.isEmpty(filteredList){
filteredList.addAll(method7())
}
return filteredList;
}

Solution

  • Only method1() matters, once the List is not empty you don't need to check it again - and if method1() doesn't add anything to the List none of the other methods appear to run. So,

    List<String> filteredList = new ArrayList<>(method1());
    if (!filteredList.isEmpty()) {
        filteredList.addAll(method2());
        filteredList.addAll(method3());
        filteredList.addAll(method4());
        filteredList.addAll(method5());
        filteredList.addAll(method6());
        filteredList.addAll(method7());
    }
    return filteredList;
    

    But, based on your prose you actually wanted something like

    List<String> filteredList = new ArrayList<>();
    if (!filteredList.addAll(method1())) {
        if (!filteredList.addAll(method2())) {
            if (!filteredList.addAll(method3())) {
                if (!filteredList.addAll(method4())) {
                    if (!filteredList.addAll(method5())) {
                        if (!filteredList.addAll(method6())) {
                            filteredList.addAll(method7());
                        }
                    }
                }
            }
        }
    }
    return filteredList;
    

    Another option, assuming you're using Java 8+, is to iterate a List of Supplier method references. Like,

    List<Supplier<Collection<String>>> func = List.of(
            this::method1, this::method2, this::method3,
            this::method4, this::method5, this::method6,
            this::method7);
    List<String> filteredList = new ArrayList<>();
    for (Supplier<Collection<String>> f : func) {
        if (filteredList.addAll(f.get())) {
            break;
        }
    }
    return filteredList;