How do I sort strings using Collator class?

In this example we demonstrate how to 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.

package org.kodejava.example.text;

import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Collections;
import java.text.Collator;

public class StringShortWithCollator {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();

        // Define a collator for US English.
        Collator collator = Collator.getInstance(Locale.US);

        // Sort the list base on the collator
        Collections.sort(fruits, collator);

        for (String fruit : fruits) {
            System.out.println("Fruit = " + fruit);

The result of the code snippet above are:

Fruit = Apple
Fruit = Banana
Fruit = Guava
Fruit = Mango
Fruit = Orange

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

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