For each loop on Java HashMap

后端 未结 4 1876
抹茶落季
抹茶落季 2021-02-05 08:21

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. Key wor

相关标签:
4条回答
  • 2021-02-05 08:57

    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:

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

    to retrieve the function (or null if the user-input does not appear in the map).

    0 讨论(0)
  • 2021-02-05 09:01

    Only in Java 8 & above

    map.forEach((k,v)->System.out.println("Key: " + k + "Value: " + v));
    
    0 讨论(0)
  • 2021-02-05 09:17

    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();
        }
    
    0 讨论(0)
  • 2021-02-05 09:21

    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.

    0 讨论(0)
提交回复
热议问题