CollationKey Sort Keys For Repeated Compare
Build each CollationKey once and sort by keys, then compare repeatedly without paying Collator.compare on every lookup during large sorts.
Code
import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;
import java.util.Locale;
public class SortedDirectory {
public static void main(String[] args) {
Collator collator = Collator.getInstance(Locale.forLanguageTag("sv-SE"));
String[] names = {"Zebra", "Ångström", "Ärzte", "Alan"};
// locale 规则一次性烘焙进键里:repeated compares read the precomputed keys
CollationKey[] keys = Arrays.stream(names)
.map(collator::getCollationKey)
.toArray(CollationKey[]::new);
Arrays.sort(keys);
for (CollationKey key : keys) {
System.out.println(key.getSourceString());
}
// 键与 Collator.compare 结论一致:比较走字节序而不是再跑一遍规则表
CollationKey a = collator.getCollationKey("Ärzte");
CollationKey b = collator.getCollationKey("Alan");
System.out.println("key compareTo < 0: " + (a.compareTo(b) < 0));
System.out.println("collator compare < 0: " + (collator.compare("Ärzte", "Alan") < 0));
}
}Inside the code
Everything happens inside the class SortedDirectory and the function main.
The file repeats itself only inside for (CollationKey key : keys).
Points of care
- The toolchain’s stock setup is enough — add nothing.
Putting it to use
Entry signature: public static void main(String[] args)
The demo output is labeled (key compareTo < 0:, collator compare < 0:), so every line of output points back to the operation that emitted it.
Core lines
Arrays.sort(keys);
.map(collator::getCollationKey)
.toArray(CollationKey[]::new);
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does CollationKey Sort Keys For Repeated Compare print when run?
- No setup needed: run the file and look for labeled lines like `key compareTo < 0:`, `collator compare < 0:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.