我有以下带有字符串数组的 HashMap :
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"});
我有一个字符串,我想在 HashMap 的字符串数组中搜索它。我的代码是:
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;
}
这将有效地迭代整个 HashMap 值,直到找到匹配项。有没有更好的方法来做到这一点?
最佳答案
根据您当前的数据结构,这是您能做的最好的事情。如果您需要经常这样做,您应该构建另一个具有相反关系的 Hashmap,其中“主题”是键,“类(class)”是值。
关于java - 在Hashmap中搜索字符串数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55854945/