Bootstrap FreeKB - Java - Return value from a hash table
Java - Return value from a 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

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.

for (Map.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 3bea88 in the box below so that we can be sure you are a human.