Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple if-else statements to optimize code?

I want to know if there is any way i could optimize this code.

String[] array;
for(String s:array){
   if(s.contains("one"))
       //call first function
   else if(s.contains("two"))
      //call second function
   ...and so on
}

The string is basically lines I am reading from a file.So there can be many number of lines.And I have to look for specific keywords in those lines and call the corresponding function.

like image 463
Anurag Upadhyaya Avatar asked Oct 18 '16 13:10

Anurag Upadhyaya


3 Answers

This wont stop you code from doing many String#contains calls, however, it will avoid the if/else chaining..

You can create a key-function map and then iterate over the entries of this map to find which method to call.

public void one() {...}
public void two() {...}
private final Map<String, Runnable> lookup = new HashMap<String, Runnable>() {{
    put("one", this::one);
    put("two", this::two);
}};

You can then iterate over the entry-set:

for(final String s : array) {
    for(final Map.Entry<String, Runnable> entry : lookup) {
        if (s.contains(entry.getKey())) {
            entry.getValue().run();
            break;
        }
    }
}
like image 106
flakes Avatar answered Oct 23 '22 14:10

flakes


You can use switch, but in this case i think the if else is the best way

like image 32
travis_91 Avatar answered Oct 23 '22 13:10

travis_91


Since you stated that the order of the checks is not important, you can use a combination of regular expression matching and switch:

static final Pattern KEYWORDS=Pattern.compile("one|two|tree|etc");

 

Matcher m=KEYWORDS.matcher("");
for(String s:array) {
    if(m.reset(s).find()) switch(m.group()) {
        case "one": //call first function
            break;
        case "two": //call second function
            break;
        case "three": //call third function
            break;
        case "etc": // etc
            break;
    }
}

Since this will stop at the first match, regardless of which keyword, it is potentially more efficient than checking one keyword after another, for strings containing a match close to the beginning.

like image 38
Holger Avatar answered Oct 23 '22 12:10

Holger