19

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

3
  • How are you storing a function in a Hashmap? Do you mean a listener? Commented Jan 4, 2013 at 1:50
  • You can get a list of keys with myHashMap.keySet() if that's what you're asking. Commented Jan 4, 2013 at 1:52
  • Possible duplicate of How to efficiently iterate over each entry in a 'Map'? Commented Mar 12, 2018 at 13:29

4 Answers 4

70

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();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

If you want immutable access to the Entry, make e final.
24

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).

Comments

12

Only in Java 8 & above

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.