Dictionary example in java

Java Dictionary example

In this tutorial we will discuss about dictionaries in Java. A Dictionary is an abstract class that maps keys to values. Every key is associated with a unique value and key are unique. Any non-null object can be used for either a key or a value. An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException . However, the original Dictionary class is now deprecated and instead, all new implementations should implement the Map interface. The Map interface provides the functionality of a dictionary, using exactly the same semantics. A Map can provide three views, which allow the contents of the map to be viewed as a set of keys, collection of values, or set of key-value mappings. Finally, some implementations of the Map interface maintain an order among its values.

The Map Interface

  • K: specifies the type of keys maintained in this map.
  • V: defines the type of mapped values.

Furthermore, the Map interface provides a set of methods that must be implemented. In this section, we will present some of the most fundamental methods of a map:

  • containsKey: Returns true if the map contains the requested key.
  • containsValue: Returns true if the map contains the requested value.
  • get: Retrieve the value of the requested key.
  • keySet: Returns a Set that contains all keys of the map.
  • put: Adds the requested key-value pair in the map.
Читайте также:  Wild python mancera 120

HashTable – HashMap

The Hashtable class implements a hash table and maps keys to values. A HashMap is a hash table based implementation of the Map interface. They both contain two fundamental parameters: initial capacity and performance. The capacity is defined as the number of buckets in the hash table, while the load factor is a measure that indicates the maximum value the hash table can reach, before being automatically increased.

An example that uses a HashMap as a dictionary is shown below. The program can also be executed properly if we change the type of our map to a Hashtable :

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; public class CountWords_v1 < public static void main(String[] args) throws IOException < BufferedReader reader = new BufferedReader(new FileReader(new File("input.txt"))); String inputLine = null; Map dictionary = new HashMap(); //Map dictionary = new Hashtable(); while((inputLine = reader.readLine()) != null) < // Split the input line. String[] words = inputLine.split("\\s+"); // Ignore empty lines. if(inputLine.equals("")) continue; for(String word: words) < // Remove any commas and dots. word = word.replace(".", ""); word = word.replace(",", ""); if(dictionary.containsKey(word)) < Integer val = dictionary.get(word); dictionary.put(word, val + 1); >else dictionary.put(word, 1); > > // Printing all words stored in the map. for(String key: dictionary.keySet()) System.out.println(key + ": " + dictionary.get(key)); reader.close(); > >

In this example we used a HashMap to store the words of a file and how many times each word appears in that file.

A sample execution is shown below:

to: 2 Geeks: 1 HashMaps: 1 is: 2 text: 1 a: 1 Also: 1 Hashtables: 1 from: 1 LinkedHashMaps: 1 the: 2 namely: 1 Maps: 1 used: 1 Code: 1 This: 1 Java: 2 and: 1 hello: 1 that: 1 present: 1 of: 2 power: 2 everybody: 1 sample: 1

LinkedHashMap

The LinkedHashMap class provides an implementation of a map that has a predictable iteration order.

Читайте также:  Javascript full stack react

The same example that counts the references of a word in a file and stores the key-value pairs in a LinkedHashMap is shown below:

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Set; public class CountWords_v2 < public static void main(String[] args) throws IOException < BufferedReader reader = new BufferedReader(new FileReader(new File("input.txt"))); String inputLine = null; LinkedHashMap dictionary = new LinkedHashMap(); while((inputLine = reader.readLine()) != null) < // Split the input line. String[] words = inputLine.split("\\s+"); // Ignore empty lines. if(inputLine.equals("")) continue; for(String word: words) < // Remove any commas and dots. word = word.replace(".", ""); word = word.replace(",", ""); if(dictionary.containsKey(word)) < Integer val = dictionary.get(word); dictionary.put(word, val + 1); >else dictionary.put(word, 1); > > // Printing all words stored in the map. Set entries = dictionary.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()) < Entry entry = iter.next(); System.out.println(entry.getKey() + ": " + entry.getValue()); >reader.close(); > >

A sample execution is shown below:

This: 1 is: 2 a: 1 sample: 1 text: 1 that: 1 used: 1 to: 2 present: 1 the: 2 power: 2 of: 2 Java: 2 Maps: 1 namely: 1 HashMaps: 1 Hashtables: 1 and: 1 LinkedHashMaps: 1 Also: 1 hello: 1 everybody: 1 from: 1 Code: 1 Geeks: 1

Notice that the usage of a LinkedHashMap enables us to print the stored keys in the way in which the words were read and stored in the map.

Download the Eclipse Project

The Eclipse project of this example: CountWords.zip

This was a tutorial about dictionaries in Java.

Источник

Dictionary class in java – Java Dictionary Class with Example | Java.util.Dictionary Class in Java | Definition, Syntax, Methods & Sample Code

Java Dictionary Class with Example

Dictionary class in java: Dictionary is an abstract class that provides a key/value storage repository and works much like Map. In this tutorial, you will review and learn about the Java Dictionary Abstract Class. By using an example you’ll easily understand the demonstration of the Dictionary usage. Have an idea about the java dictionary class definition, declaration, hierarchy, methods via direct links available below:

Java.util.Dictionary Class in Java

Java dictionary example: Java Dictionary is an abstract class, representing a key-value relation and works similar to a map. If we have a key-value pair then we can store the value in the Dictionary object. Once the value is stored in a dictionary object, we can retrieve it by using its key. In Dictionary, any non-null object can be used as a key and as a value.

dictionary class in java

Creating a Dictionary

Java dictionary example: The primary step to create a dictionary in Java is to select a class that performs a “key-value pair” interface; a few instances involve HashTables , HashMap , and LinkedHashMap .

The Dictionary object classes are implemented in java.utils package.

Declaration of Dictionary Class in java

public abstract class Dictionary extends Object

Constructors of Java Dictionary

Java Dictionary Class Hierarchy

A Diagrammatic illustration of the Dictionary class Hierarchy is as below:

dictionary hierarchy

Methods of Java Dictionary

The abstract methods specified by Java Dictionary are mentioned below:

  1. Object put(Object key, Object value): This method is used to insert a key/value pair into a Dictionary.
  2. Object get(Object key): It returns the object that contains the value associated with the key.
  3. boolean isEmpty(): It checks whether the Dictionary is empty or not. If the Dictionary is empty it will return true else return false.
  4. int size(): Returns the number of key/value pair in the dictionary.
  5. Object remove(Object key): Removes the key and its value. Declares the value associated with the key. If the key is not in the dictionary, it returns null.
  6. Enumeration elements(): This method returns an enumeration of the values contained in the dictionary.
  7. Enumeration keys(): This method returns an enumeration of the keys contained in the dictionary.

Java Dictionary Example

import java.util.*; class DictionaryExample < public static void main(String args[])< //creating a dictionary Dictionary dict = new Hashtable(); //adding values in this dictionary dict.put(101, "Rahul"); dict.put(109, "Amit"); dict.put(103, "Vijay"); dict.put(102, "Suresh"); dict.put(108, "Prashant"); //returns size of the dictionary System.out.println("Dictionary size is: "+dict.size()); //enumeration of the values contained in the dictionary. for(Enumeration enm = dict.elements(); enm.hasMoreElements();)< System.out.println("Dictionary values are: "+enm.nextElement()); >//returns the value at key 108. System.out.println("Retrieve value at key 108: " +dict.get(108)); //returns a boolean value System.out.println("Check dictionary is empty or not: " +dict.isEmpty()); //enumeration of the keys contained in the dictionary. for(Enumeration enm = dict.keys(); enm.hasMoreElements();) < System.out.println("Dictionary keys are: "+enm.nextElement()); >> >

Источник

Class Dictionary

The Dictionary class is the abstract parent of any class, such as Hashtable , which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up. Any non- null object can be used as a key and as a value.

As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class.

Constructor Summary

Method Summary

Methods declared in class java.lang.Object

Constructor Details

Dictionary

Method Details

size

isEmpty

Tests if this dictionary maps no keys to value. The general contract for the isEmpty method is that the result is true if and only if this dictionary contains no entries.

keys

Returns an enumeration of the keys in this dictionary. The general contract for the keys method is that an Enumeration object is returned that will generate all the keys for which this dictionary contains entries.

elements

Returns an enumeration of the values in this dictionary. The general contract for the elements method is that an Enumeration is returned that will generate all the elements contained in entries in this dictionary.

get

Returns the value to which the key is mapped in this dictionary. The general contract for the isEmpty method is that if this dictionary contains an entry for the specified key, the associated value is returned; otherwise, null is returned.

put

Maps the specified key to the specified value in this dictionary. Neither the key nor the value can be null . If this dictionary already contains an entry for the specified key , the value already in this dictionary for that key is returned, after modifying the entry to contain the new element. If this dictionary does not already have an entry for the specified key , an entry is created for the specified key and value , and null is returned. The value can be retrieved by calling the get method with a key that is equal to the original key .

remove

Removes the key (and its corresponding value ) from this dictionary. This method does nothing if the key is not in this dictionary.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Оцените статью