How to replace multiple if-else statements to optimize code?
contains, if-statement, java, optimization
Solution
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;
}
}
}
Problem
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.