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
A map has the form Map <K, V>
where:
- 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.
The Map
interface is implemented by different Java classes, such as HashMap
, Hashtable
and LinkedHashMap
. These classes are able to provide the full functionality of a dictionary. However, these classes differ in some key aspects, as presented below:
Null Keys | Null Values | Order | Synchronized | |
HashMap | Permitted | Permitted | No | No |
HashTable | Prohibited | Prohibited | No | Yes |
LinkedHashMap | Permitted | Permitted | Yes | No |
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
:
CountWords_v1.java:
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.
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:
CountWords_v2.java:
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<Entry> entries = dictionary.entrySet(); Iterator<Entry> 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.