如何在HashMap的所有键上循环?

Rom*_*man 1 java iterator loops hashmap

我试着用以下方式做到这一点:

public String getValue(String service, String parameter) {
    String inputKey = service + ":" + parameter;
    Set keys = name2value.keySet();
    Iterator itr = keys.iterator();
    while (itr.hasNext()) {     
        if (inputKey.equal(itr.next())) {
            return name2value.get(inputKey);
        }
        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:找不到符号method.equal(java.lang.Object).

我认为这是因为itr.next()不被视为字符串.我怎么解决这个问题?我试图取代Set keysSet<String> keys.它没有帮助.

fin*_*nnw 7

你想要的方法equals不是equal.

但是,您的代码中还存在一些其他缺陷.

首先,您不应循环遍历a中的所有键Map以查找特定键,只需使用get和/或containsKey.

第二个return也是错的.""如果第一个键不匹配,它将返回.如果您想""没有任何键匹配时返回,则return应该在方法的末尾进行,例如:

public String getValue(String service, String parameter) {
    String inputKey = service + ":" + parameter;
    String value = name2value.get(inputKey);
    if (value == null) {
        return "";
    } else {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)