How do I sort strings data using CollationKey class?

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

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.example.text;

import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;
import java.util.Collections;

public class CollationKeyExample {
    public static void main(String[] args) {
        String[] countries = {
                "United Kingdom",
                "United States",


        // 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

        // Print out the sorted array
        System.out.println("sorted result: ");
        StringBuilder sb = new StringBuilder("[");
        for (CollationKey key : keys) {
        sb.deleteCharAt(sb.length() - 1).append("]");

Below is the result of the program:

[German, United Kingdom, United States, French, Japan, Myanmar, India]
sorted result: 
[French,German,India,Japan,Myanmar,United Kingdom,United States]
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply