Programming Tutorials

Compare compareTo() function of String class with Collator and CollationKey

By: Riktesh Srivastava in Java Tutorials on 2008-04-11  

The documentation for the compareTo() method of String defines the ordering lexicographically. This means the comparison is of the numerical values of the characters in the text, which is not necessarily alphabetically in all languages. For locale-specific ordering, use Collator with CollationKey.

The following example demonstrates the use of Collator with CollationKey to do a locale-specific sorting:

import java.text.*;
import java.util.*;
public class program{
	public static void main(String args[])
	{
		Collator collator = Collator.getInstance();
		CollationKey key1 = collator.getCollationKey(\"riks\");
		CollationKey key2 = collator.getCollationKey(\"riky\");
		CollationKey key3 = collator.getCollationKey(\"riktesh\");
		CollationKey key4 = collator.getCollationKey(\"Riky\");
		CollationKey key5 = collator.getCollationKey(\"Riktesh\");

		Set set = new TreeSet();
		set.add(key1);
		set.add(key2);
		set.add(key3);
		set.add(key4);
		set.add(key5);

		Iterator iterator = set.iterator();
		System.out.print(\"[\");
		while (iterator.hasNext())
		{
			CollationKey key = (CollationKey)iterator.next();
			System.out.print(key.getSourceString());
			System.out.print(\",\");
		}

		System.out.println(\"]\");
	}
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)