Bootstrap FreeKB - Java - Loop through hash table
Java - Loop through hash table

Updated:   |  Java articles

Here is an example of how to create a hash table named myhashtable that will contain keys that are Strings and values that are Objects

import java.util.Hashtable;

public class Main {
  public static void main(String[] args){ 
    Hashtable<String, Object> myhashtable   = new Hashtable<String, Object>();

    myhashtable.put("foo", "Hello");
    myhashtable.put("bar", "World");

    System.out.println("myhashtable  = " + myhashtable);
    System.out.println("The foo key in myhashtable contains the following value:" + myhashtable.get("foo"));
  }
}

 

System.out.println should return the following.

myhashtable  = {bar=World, foo=Hello}
The foo key in myhashtable contains the following value: Hello

 

And here is how you can loop over each key value pair.

import java.util.Hashtable;
import java.util.Map.Entry;

public class test {
	  public static void main(String[] args){ 
		    Hashtable<String, Object> myhashtable = new Hashtable<String, Object>();

		    myhashtable.put("foo", "Hello");
		    myhashtable.put("bar", "World");

		    System.out.println("myhashtable  = " + myhashtable);
		    
		    for (Entry<String, Object> set : myhashtable.entrySet()) { 
		    	  System.out.println( set.getKey() + " = " + set.getValue() ); 
		    }
		  }
	  
}

 

Which should print the following.

foo = Hello
bar = World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 9b4bcf in the box below so that we can be sure you are a human.