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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books