How do I sort strings using Collator class?

Category: java.text, viewed: 5989 time(s).

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<String>();
        fruits.add("Guava");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Mango");
        fruits.add("Apple");

        //
        // Define a collator for US English.
        //
        Collator collator = Collator.getInstance(Locale.US);
        
        //
        // Sort the list base on the collator
        //
        Collections.sort(fruits, collator);

        for (int i = 0; i < fruits.size(); i++) {
            String fruit = fruits.get(i);

            System.out.println("Fruit = " + fruit);
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats