简体   繁体   English

对于Java HashMap上的每个循环

[英]For each loop on Java HashMap

A basic chat program I wrote has several key words that generate special actions, images, messages, etc. I store all of the key words and special functions in a HashMap. 我写的基本聊天程序有几个关键词,可以生成特殊的动作,图像,消息等。我将所有关键词和特殊函数存储在HashMap中。 Key words are the keys and functions are the values. 关键词是键,功能是值。 I want to compare user input to the keys with some type of loop. 我想将用户输入与键与某种类型的循环进行比较。 I have tried everything I can think of and nothing works. 我已经尝试了我能想到的一切,但没有任何作用。 This is what I can figure out: 这是我可以弄清楚的:

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

I would appreciate any help. 我将不胜感激任何帮助。 Forgive me if I overlooked a similar question or if the answer is obvious. 如果我忽略了类似的问题,或者答案是否明显,请原谅我。

If you need access to both key and value then this is the most efficient way 如果您需要访问密钥和值,那么这是最有效的方法

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

Well, you can write: 好吧,你可以写:

for(String currentKey : myHashMap.keySet()){

but this isn't really the best way to use a hash-map. 但这并不是使用哈希映射的最佳方式。

A better approach is to populate myHashMap with all-lowercase keys, and then write: 更好的方法是使用全小写键填充myHashMap ,然后编写:

theFunction = myHashMap.get(user.getInput().toLowerCase());

to retrieve the function (or null if the user-input does not appear in the map). 检索函数(如果用户输入没有出现在地图中,则返回null )。

仅限Java 8及以上版本

map.forEach((k,v)->System.out.println("Key: " + k + "Value: " + v));

A better pattern here might be: 这里更好的模式可能是:

Value val = hashMap.get(user.getInput());
if (val != null) {
    doVal();
}
else {
    // handle normal, non-keyword/specfial function
}

which takes advantage of the fact that HashMap returns null if the key isn't contained in the Map. 如果密钥未包含在Map中,则利用HashMap返回null的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM