Saturday, 12 March 2011

Basic Operations in map

The basic operations (put, get, remove, containsKey, containsValue, size, and isEmpty) behave exactly like their counterparts in Hashtable. Here's a simple program to generate a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the argument list.
import java.util.*;

public class Freq {
private static final Integer ONE = new Integer(1);

public static void main(String args[]) {
Map m = new HashMap();

// Initialize frequency table from command line
for (int i=0; i<args.length; i++) {
Integer freq = (Integer) m.get(args[i]);
m.put(args[i], (freq==null ? ONE :
new Integer(freq.intValue() + 1)));
}

System.out.println(m.size()+" distinct words detected:");
System.out.println(m);
}
}
The only thing even slightly tricky about this program is the second argument of the put statement. It's a conditional expression that has the effect of setting the frequency to one if the word has never been seen before, or one more than its current value if the word has already been seen. Let's run the program:
% java Freq if it is to be it is up to me to delegate

8 distinct words detected:
{to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1}
Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the Map from HashMap to TreeMap. Making this four character change causes the program to generate the following output from the same command line:
8 distinct words detected:
{be=1, delegate=1, if=1, is=2, it=2, me=1, to=3, up=1}
Are interfaces cool, or what? Like the Set(in the API reference documentation)and List(in the API reference documentation)interfaces, Map strengthens the requirements on the equals and hashCode methods so that two Map objects can be compared for logical equality without regard to their implementation types. Two Map objects are equal if they represent the same key-value mappings.
By convention, all Map implementations provide constructors that take a Map object and initialize the new Map to contain all of the key-value mappings in the specified Map. This standard Map constructor is entirely analogous to the standard collection constructor for Collection implementations. It allows the caller to create a Map of a desired implementation type that initially contains all of the mappings in another Map, regardless of the other Map's implementation type. For example, suppose you have a Map, named m. The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m:
Map copy = new HashMap(m);

No comments:

Post a Comment