对于Java HashMap上的每个循环

Tax*_*s45 19 java loops hashmap

我写的基本聊天程序有几个关键词,可以生成特殊动作,图像,消息等.我将所有关键词和特殊函数存储在HashMap中.关键词是键,功能是值.我想将用户输入与键与某种类型的循环进行比较.我已经尝试了我能想到的一切,但没有任何作用.这是我可以弄清楚的:

myHashMap = <File Input>
for(String currentKey : <List of HashMap Keys>){
    if(user.getInput().equalsIgnoreCase(currentKey)){
        //Do related Value action
    }
}
...
Run Code Online (Sandbox Code Playgroud)

我将不胜感激任何帮助.如果我忽略了类似的问题,或者答案是否明显,请原谅我.

Evg*_*eev 66

如果您需要访问密钥和值,那么这是最有效的方法

    for(Entry<String, String> e : m.entrySet()) {
        String key = e.getKey();
        String value = e.getValue();
    }
Run Code Online (Sandbox Code Playgroud)

  • 这正是我想要的! (2认同)

rua*_*akh 23

好吧,你可以写:

for(String currentKey : myHashMap.keySet()){
Run Code Online (Sandbox Code Playgroud)

但这并不是使用哈希映射的最佳方式.

更好的方法是myHashMap使用全小写键填充,然后编写:

theFunction = myHashMap.get(user.getInput().toLowerCase());
Run Code Online (Sandbox Code Playgroud)

检索函数(或者null如果用户输入没有出现在地图中).


Thi*_*mal 10

仅限Java 8及以上版本

map.forEach((k,v)->System.out.println("Key: " + k + "Value: " + v));
Run Code Online (Sandbox Code Playgroud)