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.

JavaData Integrity

Code

snippet
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

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.