 |
|
|
Uniq.java
|
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
*
* Example using HashMap, for-each loop and auto-boxing
* to count the number of occurrences of words in the input
* String.
*
* One can switch between sorted and unsorted output by using
* either the TreeMap or HashMap implementation.
*
* The implementation does not check for non-alphabetical
* characters.
*
*/
public class Uniq {
/**
* Constructs the Uniq counter which outputs to screen
* its end result.
*
* @param words an array of words
*/
public Uniq(String words[]) {
//don't bother if there's nothing to count
if(words == null || words.length == 0) {
System.out.println("Usage: java Uniq <string of words>");
return;
}
Map map = countWords(words);
showCount(map);
}
/**
* Count the number of occurrences of each word.
* Each unique word is created as a String key in the Map
* while each value is an Integer for the word count.
*
* @param words
* @return
*/
private Map countWords(String words[]) {
Map map = new HashMap();
//loop through all words using the for-each loop
for(String word : words) {
//if the word exists as a key already,
//increase the count, otherwise insert with
//a count of 1.
if(map.containsKey(word)) {
int count = (Integer)map.get(word);
map.put(word, count+1);
}
else {
map.put(word, 1);
}
}
return map;
}
/**
* Prints the contents of a Map containing
* word keys and count values.
*
* The keys are Strings and the values Integers.
*
* @param map word count map to print to screen
*/
private void showCount(Map map) {
//iterate all the keys of the map using
//the for-each loop
for(Object word : map.keySet()) {
int count = (Integer)map.get(word);
System.out.println(""+word+": "+count);
}
}
public static void main(String[] args) {
new Uniq(args);
}
}
|
|
|
 |