Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close