Trusted answers to developer questions

Java Dictionary

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A java dictionary is an abstract class that stores key-value pairs. Given a key, values can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. Classes that implement this kind of interface include HashTables, HashMap, LinkedHashMap, etc.

The Dictionary object class is implemented in java.utils.

svg viewer

There are some Dictionary implementations that also ​allow various values to be referenced with a single key.

Class methods

  • Dictionary(): the default constructor.

  • elements(): returns the enumeration of all the values in the dictionary.

  • isEmpty(): checks whether or not the dictionary is empty.

  • keys(): returns the enumeration of all the keys in the dictionary.

  • put(K key, V value): adds the key-value pair to the dictionary.

  • remove(K key): removes the key-value pair that was mapped with the specified key.

  • get(K key): returns the value that was mapped to the specified ​key.

  • size():​ returns the number of key-value pairs in the Dictionary.

Code

The usage of the above methods is illustrated in the code snippet below:

import java.util.*;
class My_Dictionary
{
public static void main(String[] args)
{
// initializing My HashTable Dictionary
Hashtable<String, String> my_dict = new Hashtable<String, String>();
// using elements() method
for (Enumeration x = my_dict.elements(); x.hasMoreElements();)
{
System.out.println("Values in my_dict: " + x.nextElement());
}
// using isEmpty() method
System.out.println("\nIs my dictionary empty?: " + my_dict.isEmpty() + "\n");
// using keys() method
for (Enumeration x = my_dict.keys(); x.hasMoreElements();)
{
System.out.println("Keys in my_dict: " + x.nextElement());
}
// using put method
my_dict.put("01", "Apple");
my_dict.put("10", "Banana");
// using remove() method
// remove value at key 10
my_dict.remove("10");
System.out.println("Checking if the removed value exists: " + my_dict.get("10"));
// using get() method
System.out.println("\nValue at key = 10: " + my_dict.get("10"));
System.out.println("Value at key = 11: " + my_dict.get("11"));
// using size() method
System.out.println("\nSize of my_dict : " + my_dict.size());
}
}

RELATED TAGS

dictionary
class
object
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?