Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each loop on Java HashMap

Tags:

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.

like image 762
Taxes45 Avatar asked Jan 04 '13 01:01

Taxes45


People also ask

Can we use for-each loop for HashMap in Java?

We can use the Java for-each loop to loop through each entry of the hashmap.

How many ways we can iterate HashMap in Java?

There are generally five ways of iterating over a Map in Java.

Can u iterate HashMap explain in with program?

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.


1 Answers

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();
    }
like image 76
Evgeniy Dorofeev Avatar answered Sep 30 '22 05:09

Evgeniy Dorofeev