전체 페이지뷰

2016년 12월 27일 화요일

Java Dictionary example

https://examples.javacodegeeks.com/java-basics/data-types/java-dictionary-example/

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 Mapinterface 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 HashMapHashtable 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:
01import java.io.BufferedReader;
02import java.io.File;
03import java.io.FileReader;
04import java.io.IOException;
05import java.util.HashMap;
06import java.util.Hashtable;
07import java.util.Map;
08
09public class CountWords_v1 {
10     
11    public static void main(String[] args) throws IOException {
12        BufferedReader reader = new BufferedReader(new FileReader(new File("input.txt")));
13        String inputLine = null;
14        Map dictionary = new HashMap();
15        //Map dictionary = new Hashtable();
16         
17        while((inputLine = reader.readLine()) != null) {
18            // Split the input line.
19            String[] words = inputLine.split("\\s+");
20             
21            // Ignore empty lines.
22            if(inputLine.equals(""))
23                continue;
24             
25            for(String word: words) {
26                // Remove any commas and dots.
27                word = word.replace(".""");
28                word = word.replace(",""");
29                 
30                if(dictionary.containsKey(word)) {
31                    Integer val = dictionary.get(word);
32                    dictionary.put(word, val + 1);
33                }
34                else
35                    dictionary.put(word, 1);
36            }
37        }
38         
39        // Printing all words stored in the map.
40        for(String key: dictionary.keySet())
41            System.out.println(key + ": " + dictionary.get(key));
42         
43         
44        reader.close();
45    }
46}
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:
01import java.io.BufferedReader;
02import java.io.File;
03import java.io.FileReader;
04import java.io.IOException;
05import java.util.Iterator;
06import java.util.LinkedHashMap;
07import java.util.Map.Entry;
08import java.util.Set;
09
10public class CountWords_v2 {
11     
12    public static void main(String[] args) throws IOException {
13        BufferedReader reader = new BufferedReader(new FileReader(new File("input.txt")));
14        String inputLine = null;
15        LinkedHashMap dictionary = new LinkedHashMap();
16         
17        while((inputLine = reader.readLine()) != null) {
18            // Split the input line.
19            String[] words = inputLine.split("\\s+");
20             
21            // Ignore empty lines.
22            if(inputLine.equals(""))
23                continue;
24             
25            for(String word: words) {
26                // Remove any commas and dots.
27                word = word.replace(".""");
28                word = word.replace(",""");
29                 
30                if(dictionary.containsKey(word)) {
31                    Integer val = dictionary.get(word);
32                    dictionary.put(word, val + 1);
33                }
34                else
35                    dictionary.put(word, 1);
36            }
37        }
38         
39        // Printing all words stored in the map.
40        Set<Entry> entries = dictionary.entrySet();
41        Iterator<Entry> iter = entries.iterator();
42         
43        while(iter.hasNext()) {
44            Entry entry = iter.next();
45            System.out.println(entry.getKey() + ": " + entry.getValue());
46        }
47         
48        reader.close();
49    }
50}
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.

댓글 없음:

댓글 쓰기