How do I sort an array of string data using RuleBasedCollator class?

We can use the java.text.Collator class to sort strings in language-specific order. Using the java.text.Collator class makes the string not just sorted by the ASCII code of their characters but it will follow the language natural order of the characters.

If the predefined collation rules do not meet your needs, you can design your own rules and assign them to a RuleBasedCollator object. Customized collation rules are contained in a String object that is passed to the RuleBasedCollator constructor.

package org.kodejava.example.text;

import java.text.Collator;
import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.Arrays;
import java.util.Collections;

public class RuleBasedCollatorDemo {
    public static void main(String[] args) {
        String rule1 = ("< a < b < c");
        String rule2 = ("< c < b  < a");
        String rule3 = ("< c < a  < b");

        String words[] = {
                "apple",
                "banana",
                "carrot",
                "apricot",
                "blueberry",
                "cabbage"
        };

        try {
            RuleBasedCollator rb1 = new RuleBasedCollator(rule1);
            RuleBasedCollator rb2 = new RuleBasedCollator(rule2);
            RuleBasedCollator rb3 = new RuleBasedCollator(rule3);

            System.out.println("original: ");
            System.out.println(Arrays.toString(words));

            //
            // Sort based on rule1
            //
            Collections.sort(Arrays.asList(words), rb1);
            System.out.println("nrule: " + rb1.getRules());
            System.out.println(Arrays.toString(words));

            //
            // Sort based on rule2
            //
            Collections.sort(Arrays.asList(words), rb2);
            System.out.println("nrule: " + rb2.getRules());
            System.out.println(Arrays.toString(words));

            //
            // Sort based on rule3
            //
            Collections.sort(Arrays.asList(words), rb3);
            System.out.println("nrule: " + rb3.getRules());
            System.out.println(Arrays.toString(words));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Below is the result of sorting strings using a different RuleBasedCollator

original: 
[apple, banana, carrot, apricot, blueberry, cabbage]

rule: < a < b < c
[apple, apricot, banana, blueberry, cabbage, carrot]

rule: < c < b  < a
[cabbage, carrot, banana, blueberry, apple, apricot]

rule: < c < a  < b
[cabbage, carrot, apple, apricot, banana, blueberry]
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, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply