A Java dictionary is an abstract class that stores key-value pairs. Given a key, its corresponding value can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs.
The
Dictionary
object classes are implemented injava.util
.
The first step to creating a dictionary in Java is to choose a class that implements a “key-value pair” interface; a few examples include HashTables
, HashMap
, and LinkedHashMap
.
The declaration and initialization of a dictionary follows the syntax below:
The code snippet below illustrates how to create a dictionary in Java and the usage of a few of the class’s methods:
import java.util.*;class My_Dictionary{public static void main(String[] args){// creating a My HashTable DictionaryHashtable<String, String> my_dict = new Hashtable<String, String>();// Using a few dictionary Class methods// using put methodmy_dict.put("01", "Apple");my_dict.put("10", "Banana");// using get() methodSystem.out.println("\nValue at key = 10 : " + my_dict.get("10"));System.out.println("Value at key = 11 : " + my_dict.get("11"));// using isEmpty() methodSystem.out.println("\nIs my dictionary empty? : " + my_dict.isEmpty() + "\n");// using remove() method// remove value at key 10my_dict.remove("10");System.out.println("Checking if the removed value exists: " + my_dict.get("10"));System.out.println("\nSize of my_dict : " + my_dict.size());}}
Free Resources