SEMrush

Do you know to iterate through hash tables ?

Java Algorithm  - How to iterate through Hashtable ?

Dear friends, are you also confused when you have to iterate through a hash table? To tell you frankly, I was very confused initially when  I had to do this. But gradually i learnt and today I will take you through very easy steps on iterating over a Hash Table functions , that I had learnt through my journey .

Lets see how we can do the following using a Hash Table:


  • Creating an Instance of a Hash Table
  • Adding Keys and Values to the Hash Table
  • Finally, iterating through the hash table

Hashtable Iterator example 
  1. For this you need to import java.util.Hashtable same way as we always do when we are working with hash tables.
  2. Create a class with its main() method as static .
  3. Create instance of Hash Table Hashtable NameofHashTable = new Hashtable();
  4. Add Key , Value pair to the Hash Table NameofHashTable .put(KEY , VALUE) ;
  5. Iterate through the hash table with following lines of code 

                Set keys = hasht.keySet();
                for(String key: keys){
                        System.out.println("Value of "+key+" is: "+hasht.get(key));
                }

Please note : Hash Table methods keySet() and get(key) to obtain a set of Keys and get one particular key , respectively 


Java Hash Table Program


Dear friends, you opinions and comments are most welcome . Please leave a comment in the section below to let us know what you feel about the site and if any topic that you would want us to write on .







Comments