0

我想将字符串与哈希图中的键进行比较。我尝试使用此处提到的步骤将地图键与字符串列表进行比较,但对我不起作用。

哈希图包含许多条目,并且想要比较我传递的字符串。如果键与字符串匹配,它应该停在那里并打印匹配字符串的值。下面是我的代码:

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");
    }
}
4

4 回答 4

4

这对你有用

    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");
    }

输出。

    Matched key = ABC
于 2013-09-26T04:13:44.483 回答
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;
            }
        }
于 2013-09-26T04:04:06.103 回答
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");
 }
}
于 2013-09-26T03:58:13.597 回答
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");
于 2013-09-26T04:25:01.353 回答