Tuesday 21 September 2010

Comparators

The key-value (Map.Entry) pairs in a HashMap are not sorted, but users would certainly like to see them sorted, either alphabetically by word, or by frequency.
Because sorts are usually based on comparison of two values at a time, all that is needed is a way to compare two values. That's what a Comparator does -- it defines a compare() method that tells how two values compare.

import java.util.*;

/////////////////////////////////////////////////////// class ComparatorAlphabetic
/** Order words alphabetically. */
class ComparatorAlphabetic implements Comparator> {
public int compare(Map.Entry entry1
, Map.Entry entry2) {
return entry1.getKey().compareTo(entry2.getKey());
}
 
import java.util.*;

////////////////////////////////////////////////////// class ComparatorFrequency
/** Order words from least to most frequent, put ties in alphabetical order. */
class ComparatorFrequency implements Comparator> {
public int compare(Map.Entry obj1
, Map.Entry obj2) {
int result;
int count1 = obj1.getValue().value;
int count2 = obj2.getValue().value;
if (count1 < count2) {
result = -1;

} else if (count1 > count2) {
result = 1;

} else {
//... If counts are equal, compare keys alphabetically.
result = obj1.getKey().compareTo(obj2.getKey());
}
return result;
}
}  

No comments:

Post a Comment