How to replace multiple if-else statements to opti

2019-06-26 08:43发布

问题:

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.

回答1:

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;
        }
    }
}


回答2:

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



回答3:

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.