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() )
System.out.println("\t"+
( (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
Collator.PRIMARY
Dick
tom
Tony
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?