2013-09-26 105 views
-1

我想将字符串与哈希表中的关键字进行比较。我试图使用Compare map key with a list of strings这里提到的步骤,但没有为我工作。将哈希映射关键字与字符串进行比较

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

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

除非我完全误解了问题,你可以做'如果(myObjs.containsKey(的itemId))' – Thilo

+1

这是非常不清楚你想要什么在这里做。哪个“关键”,以及你想要比较的是什么?你为什么不使用'containsKey'? – chrylis

+1

你的问题非常模糊。你在标题中提到'HashMap',不要在你的代码中正确使用它,但是需要检查它的内容吗?!它引起人们以不同的方式解读它,并张贴可能不是你期待的答案! – SudoRahul

回答

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

出放。

Matched key = ABC 
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"); 
} 
} 
+0

没有解释?只是“注意不同之处?” – Bucket

+0

另外,地图在哪里使用?我真的怀疑这个OP是否有这个功能! – SudoRahul

+0

OP本身不使用它,它是一个任意的对象类型。他怎么知道如何使用它? – dajavax

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