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

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

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
            Arrays.sort(words, rb1);
            System.out.println("rule: " + rb1.getRules());
            System.out.println(Arrays.toString(words));

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

            // Sort based on rule3
            Arrays.sort(words, rb3);
            System.out.println("rule: " + 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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.