我想将字符串与hashmap中的键进行比较。我尝试使用此处提到的步骤Compare map key with a list of strings,但对我不起作用。
hashmap包含许多条目,并希望比较我传递的字符串。如果键匹配字符串,它应该停在那里并打印匹配字符串的值。 以下是我的代码:
HashMap<String, MyBO> myObjs = MyData.getMyData();
Set<String> keys = myObjs.keySet();
String id = "ABC";
for(String code: keys) {
MyBO bo = myObjs.get(code);
if(keys.contains(itemId)) {
System.out.println("Matched key = " + id);
} else {
System.out.println("Key not matched with ID");
}
}
答案 0 :(得分:3)
这对你有用
HashMap<String, MyBO> myObjs = MyData.getMyData();
String id = "ABC";
if(myObjs.containsKey(id)){
System.out.println("Matched key = " + id);
} else{
System.out.println("Key not matched with ID");
}
例如,请考虑以下示例
HashMap<String, String> myObjs =new HashMap<>();
myObjs.put("ABC","a");
myObjs.put("AC","a");
String id = "ABC";
if(myObjs.containsKey(id)){
System.out.println("Matched key = " + id);
} else{
System.out.println("Key not matched with ID");
}
Out put。
Matched key = ABC
答案 1 :(得分:1)
尝试使用此代码并将其与您的代码要求相似,它将适用于您
for (String key:keys){
String value = mapOfStrings.get(key);
//here it must uderstand, that the inputText contains "java" that equals to
//the key="java" and put in outputText the correspondent value
if (inputText.contains(key))
{
outputText = value;
}
}
答案 2 :(得分:0)
以下是您要找的内容,请注意与您的代码的不同之处:
HashMap<String, MyBO> myObjs = MyData.getMyData();
Set<String> keys = myObjs.keySet();
String id = "ABC";
for(String code: keys) {
if(code.equals(id) { /* this compares the string of the key to "ABC" */
System.out.println("Matched key = " + id);
} else {
System.out.println("Key not matched with ID");
}
}
或者,您可以这样做:
HashMap<String, MyBO> myObjs = MyData.getMyData();
Set<String> keys = myObjs.keySet();
if(keys.contains("ABC") { /* this checks the set for the value "ABC" */
System.out.println("Matched key = ABC");
} else {
System.out.println("Key not matched with ID");
}
}
答案 3 :(得分:0)
试试这种方式,
HashMap<String, String> dataArr = new HashMap<>();
dataArr.put("Key 1", "First String");
String keyValueStr = dataArr.keySet().toString();
String matchValueStr = "Key 1";
//System.out.println(keyValueStr);
if(keyValueStr.equals("["+matchValueStr+"]"))
System.out.println("Match Found");
else
System.out.println("No Match Found");