Simple Dictionary Class Example in Java

In this tutorial, I am sharing the simple program about, Simple Dictionary Class Example in Java. The example program has been shared in the same post.

DictionaryExample.java

package com.dineshkrish.utilities;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class DictionaryExample {
public static void main(String[] args) {
Dictionary<Integer, String> dictionary = new Hashtable<Integer, String>() ;
// Adding the elements to dictionary Object
dictionary.put(1, "One");
dictionary.put(2, "Two");
dictionary.put(3, "Three");
dictionary.put(4, "Four");
dictionary.put(5, "Five");
System.out.println("Getting Single Value using Key");
System.out.println("--------------------------------");
// Getting single value from Dictionary by passing Key
String value = dictionary.get(4);
System.out.println("Value of 4(Key) : "+value);
System.out.println("\nGetting all values from dictionary object by doing iteration");
System.out.println("-------------------------------------------------------------");
// Getting all keys
Enumeration<Integer> keys = dictionary.keys();
// Iteration
while(keys.hasMoreElements()) {
Integer key = keys.nextElement();
// Getting the value passing the key as parameter
System.out.println(dictionary.get(key));
}
}
}

Output

—————–

Getting Single Value using Key
——————————–
Value of 4(Key) : Four

Getting all values from dictionary object by doing iteration
————————————————————-
Five
Four
Three
Two
One

References

1. Java API Documentaion

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *