How to Use Collator and CollationKey to Do a Locale-Specific Sorting?

Collator Class contains methods used to sort and arrange strings of Unicode characters based on their decomposition and strength.

CollationKey represents the collation order of a particular String for a specific Collator. CollationKeys can be compared to determine the relative ordering of their source Strings. This is useful when the Strings must be compared multiple times, as in sorting.

The here is an example:

public class Program { 
public static void show( String tag, Collator collator )

TreeSet set = new TreeSet();

System.out.println( tag );

CollationKey key1 = collator.getCollationKey( "tom" );
CollationKey key2 = collator.getCollationKey( "Dick" );
CollationKey key3 = collator.getCollationKey( "Tony" );
set.add( key1 );
set.add( key2 );
set.add( key3 );
Iterator iterator =set.iterator();
while ( iterator.hasNext() )
( (CollationKey)iterator.next()).getSourceString() );

public static void main(String[] args) {

Collator collator = Collator.getInstance();
collator.setStrength( Collator.PRIMARY );
show( "Collator.PRIMARY", collator );


TreeSet stores objects in a sorted manner. TreeSet stores its elements in a tree and they are automatically arranged in a sorted order. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.

CollationKeys implements compareTo method. A TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal.

The output result from the above example is


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |