Search code examples
javaprefix-tree

How to remove large if-else-if chain with the condition as String::startswith


How can I avoid this if-else chain? Moving this logic to switch case looks difficult, since this code flow does some sort of prefix matching and does something based on if the condition is true.

if (fullPathWithPrefix.startsWith("A")) {
    doA();
} else if (fullPathWithPrefix.startsWith("B")) {
    doB();
} else if (fullPathWithPrefix.startsWith("C")) {
    doC();
} else if (fullPathWithPrefix.startsWith("D")) { 
    doD();
} else if (fullPathWithPrefix.startsWith("E")) {
    doE();
}

Solution

  • This solution maybe cumbersome for your case. But if your target methods can be brought under one functional interface you can do something like this:

    interface MyFunction {
        void doSomething();
    }
    
    class Main {
        public static void main(String[] args) {
            String fullPathWithPrefix = "Be careful";
            Map<String, MyFunction> prefixToTaskMap = Map.of(
                    "A", Main::doA,
                    "B", Main::doB,
                    "C", Main::doC,
                    "D", Main::doD,
                    "E", Main::doE);
    
            for (Map.Entry<String, MyFunction> entry :prefixToTaskMap.entrySet()) {
                if (fullPathWithPrefix.startsWith(entry.getKey())) {
                    entry.getValue().doSomething();
                    // If one match found, no need to match others
                    break;
                }
            }
        }
    
        private static void doE() {
            System.out.println("E");
        }
    
        private static void doD() {
            System.out.println("D");
        }
    
        private static void doC() {
            System.out.println("C");
        }
    
        private static void doB() {
            System.out.println("B");
        }
    
        private static void doA() {
            System.out.println("A");
        }
    }
    

    I have created a new functional interface MyInterface. But your may match any of the standard functional interfaces in java.util.Function