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.
We can use the Java for-each loop to loop through each entry of the hashmap.
There are generally five ways of iterating over a Map in Java.
keyset(): A keySet() method of HashMap class is used for iteration over the keys contained in the map. It returns the Set view of the keys. values(): A values() method of HashMap class is used for iteration over the values contained in the map. It returns a collection view of the values.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With