I have a hash map which maps to some strings which serve as prefixes and are of small length (max length is 6):
Map<String, String> map = new HashMap<>();
map.put("codeA", "100");
map.put("codeB", "7");
map.put("codeC", "0012");
etc
This is fine so far, but I also need when provided an input string to actually break it into 2 parts if the string has a prefix that matches one of the values in my map.
What I do is:
boolean found = false;
String [] result;
for(Entry<String, String> e: map.entrySet()) {
String code = e.getKey();
String value = e.getValue();
if(value.length >= inputString.length) continue;
if(inputString.startsWith(value)) {
result = new String[2];
result[0] = value;
result[1] = inputString.substring(value.length + 1);
found = true;
break;
}
}
return result;
Could this be improved? Could I have been using some additional datastructure/API for this?
I am interested in an approach in Java 7 without any extra libs. The HashMap has ~400 entries and the input string 8-11 characters.
I would need a way to get the prefix having the code (hence the HashMap) and break the input string into the prefix and the rest part.
Java 7 without any extra libsdoes this rule out open coding / roll-your-own? \$\endgroup\$inputString.substring(value.length + 1)? Doesn't that meaninputString.equals(result[0] + result[1])isfalse?) \$\endgroup\$