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 theif/else
chaining..You can create a key-function map and then iterate over the entries of this map to find which method to call.
You can then iterate over the entry-set:
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
: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.