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.
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;
}
}
}
You can use switch, but in this case i think the if else is the best way
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With