我需要搜索存储在LinkedHashMap中的匹配值对。
我尝试了以下代码,但它为存在的任何值提供 true,但我只希望当相应的值与键值匹配时它返回 true。
bt2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if(CheckValueExample.checkRelationship(txtKey.getText(),txtValue.getText())==true)
System.out.println("Pair Match");
else
System.out.println("No-Pair Match");
} catch (Exception ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
配对方法:
public static boolean checkRelationship(String key, String value) {
HashMap<String, String> hashmap = new LinkedHashMap<String, String>();
// Adding Key and Value pairs to HashMap
hashmap.put("Bus","Land_Vehicle");
hashmap.put("SchoolBus","Bus");
hashmap.put("Truck","Land_Vehicle");
hashmap.put("Land_Vehicle","Vehicle");
boolean flag=false;
if(hashmap.containsKey(key)&&hashmap.containsValue(value))
flag=true;
else
flag=false;
return flag;
}
假设输入的键是"总线",输入的值是"Land_Vehicle";只有这样它才应该返回 true。
任何其他替代方法也是可观的,基本上我必须匹配存储在 json 文件中的对。
只需使用 hashmap.containsKey(key) && hashmap.get(key).equals(value)
来检查关系。
它获取key
的值(如果存在(,并将其与给定的value
进行比较。
这是完整的方法:
public static boolean checkRelationship(String key, String value) {
return hashmap.containsKey(key) && hashmap.get(key).equals(value);
}
您还应该只初始化一次HashMap
(例如,在static {}
块中(,而不是每次调用该方法时。