When the strings must be compared multiple times, for example when sorting a list of strings. It’s more efficient to use CollationKey
class. Using CollationKey
to compare strings is generally faster than using Collator.compare()
.
You can not create CollationKey
directly. Rather, generate them by calling Collator.getCollationKey()
method. You can only compare CollationKey
generated from the same Collator
object.
package org.kodejava.text;
import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;
public class CollationKeyExample {
public static void main(String[] args) {
String[] countries = {
"German",
"United Kingdom",
"United States",
"French",
"Japan",
"Myanmar",
"India"
};
System.out.println("original:");
System.out.println(Arrays.toString(countries));
// Gets Collator object of default locale
Collator collator = Collator.getInstance();
// Creates and initializes CollationKey array
CollationKey[] keys = new CollationKey[countries.length];
for (int i = 0; i < countries.length; i++) {
// Generate CollationKey by calling
// Collator.getCollationKey() method then assign into
// keys which is an array of CollationKey.
// The CollationKey for the given String based on the
// Collator's collation rules.
keys[i] = collator.getCollationKey(countries[i]);
}
// Sort the keys array
Arrays.sort(keys);
// Print out the sorted array
System.out.println("sorted result: ");
StringBuilder sb = new StringBuilder();
for (CollationKey key : keys) {
sb.append(key.getSourceString()).append(",");
}
System.out.println(sb);
}
}
Below is the result of the program:
original:
[German, United Kingdom, United States, French, Japan, Myanmar, India]
sorted result:
French,German,India,Japan,Myanmar,United Kingdom,United States,