Java Reference
In-Depth Information
Determining collation factors for a string can be expensive. A
Colla-
tionKey
object examines a string once, so you can compare precomputed
keys instead of comparing strings with a
Collator
. The method
Collat-
or.getCollationKey
returns a key for a string. For example, because
Col-
lator
implements the interface
Comparator
, you could use a
Collator
to
maintain a sorted set of strings:
class CollatorSorting {
private TreeSet<String> sortedStrings;
CollatorSorting(Collator collator) {
sortedStrings = new TreeSet<String>(collator);
}
void add(String str) {
sortedStrings.add(str);
}
Iterator<String> strings() {
return sortedStrings.iterator();
}
}
Each time a new string is inserted in
sortedStrings
, the
Collator
is used
as a
Comparator
, with its
compare
method invoked on various elements
of the set until the
TReeSet
finds the proper place to insert the string.
This results in several comparisons. You can make this quicker at the
cost of space by creating a
treeMap
that uses a
CollationKey
to map to
the original string.
CollationKey
implements the interface
Comparable
with
a
compareTo
method that can be much more efficient than using
Collat-
or.compare
.
class CollationKeySorting {
private TreeMap<CollationKey, String> sortedStrings;
private Collator collator;