I have following hashmap with a string array:
public static HashMap<String, String[]> map = new HashMap<String, String[]>();
map.put("calculus",new String[] {"math","logic"});
map.put("chemisty",new String[] {"ions","electrons"});
map.put("biology",new String[] {"life","bacteria"});
I have a string which I want to search in the String arrays in the Hashmap. My code is:
public String findFn(String myString) {
for (Map.Entry<String, String[]> entry : map.entrySet()) {
String key = entry.getKey();
for(String s : entry.getValue()) {
if(s.contains(myString)) {
return key;
}
}
}
return null;
}
This would effectively iterate through entire hashmap values until the match is found. Is there any better way to do this?
arrayElement -> key(if this search happens very often)