Saturday, February 09, 2008

Sorting with Different Locale

Sorting is always a tricky game in any language. Language like Java has its own high class sorting API's. But have you ever think, how sorting works in different locales ? How it work in French or in Spanish? Lets have a look...

This is my String Array which I want to sort:
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
It contains words of French Locale(some of my fav. words like Où :-) )
And here goes our typical sorting program:

String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

And the result:
Où facil fast fácil ou specific spécifique êtes-vous

Result can surprise you and can make your French friend angry :-) because he never want "fast" should come before "fácil", just because there is one special 'á' (sorting is true according to UNICODE sequence but not according to locale)

To face this problem JDK comes with something called Collator (I guess in 1.4 onwards) which take care of locale while sorting.
Collator is an abstract class. You can look the source code at location in Openjdk: jdk\src\share\classes\java\text\Collator.java. Highly documented file.

Collator has some flavors like PRIMARY, SECONDARY, TERTIARY, IDENTICAL which all tells what need to take care while sorting. Please read the javadoc for detail.

Now here is my simple code:

import java.text.*;
import java.util.*;


class CollatorTest {

public static void main(String[] args) {
String[] names = {"fácil", "facil", "fast","Où", "êtes-vous", "spécifique", "specific", "ou"};
List list = Arrays.asList(names);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext()) {
System.out.print(itr.next()+ " ");
}

Locale[] loc = Collator.getAvailableLocales();

/* for(int i=0;
&<
{
System.out.println(loc[i].getDisplayName());
}
*/
Collator myCollator = Collator.getInstance(new Locale("fr"));
myCollator.setStrength(Collator.PRIMARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}

myCollator.setStrength(Collator.TERTIARY);
Collections.sort(list, myCollator);
itr = list.iterator();
System.out.println("");
while(itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}

And here is the result:
Où facil fast fácil ou specific spécifique êtes-vous
êtes-vous facil fácil fast Où ou specific spécifique
êtes-vous facil fácil fast ou Où specific spécifique

First one is the normal sorting, second and third is Collator sorting with 2 different types. You can very easily see that we are giving respect to other locale as well in sorting. There are 2-3 line comments in the code, which will tell which all locale Collator is supporting.

7 comments:

Anonymous said...

i have seen your web page its interesting and informative.
I really like the content you provide in the web page.
But you can do more with your web page spice up your page, don't stop providing the simple page you can provide more features like forums, polls, CMS,contact forms and many more features.
Convert your blog "yourname.blogspot.com" to www.yourname.com completely free.
free Blog services provide only simple blogs but we can provide free website for you where you can provide multiple services or features rather than only simple blog.
Become proud owner of the own site and have your presence in the cyber space.
we provide you free website+ free web hosting + list of your choice of scripts like(blog scripts,CMS scripts, forums scripts and may scripts) all the above services are absolutely free.
The list of services we provide are

1. Complete free services no hidden cost
2. Free websites like www.YourName.com
3. Multiple free websites also provided
4. Free webspace of1000 Mb / 1 Gb
5. Unlimited email ids for your website like (info@yoursite.com, contact@yoursite.com)
6. PHP 4.x
7. MYSQL (Unlimited databases)
8. Unlimited Bandwidth
9. Hundreds of Free scripts to install in your website (like Blog scripts, Forum scripts and many CMS scripts)
10. We install extra scripts on request
11. Hundreds of free templates to select
12. Technical support by email

Please visit our website for more details www.HyperWebEnable.com and www.HyperWebEnable.com/freewebsite.php

Please contact us for more information.


Sincerely,

HyperWebEnable team
info@HyperWebEnable.com

Anonymous said...

Bonjour, java4ever.blogspot.com!
[url=http://farmaciacialis.fora.pl/ ] cialis online[/url] [url=http://cialisfarmacia.fora.pl/ ]venta de cialis [/url] [url=http://medicocialis.fora.pl/ ]venta de cialis [/url] [url=http://cialisbarata.fora.pl/ ]vendo cialis online[/url] [url=http://escialisonline.fora.pl/ ]vendo cialis en espana[/url] [url=http://cialismasbarata.fora.pl/ ]vendo cialis online[/url]

Anonymous said...

lesbian at parties best lesbian bondage movie clips fat lesbians hardcore lesbian ass licking movie hot lesbian anime girls ebony pussy lesbian dildo indian teen lesbian video dump

Anonymous said...

Hello, as you may already discovered I am fresh here.
In first steps it's really nice if someone supports you, so hope to meet friendly and helpful people here. Let me know if I can help you.
Thanks and good luck everyone! ;)

Anonymous said...

I am able to make link exchange with HIGH pr pages on related keywords like [url=http://www.usainstantpayday.com]bad credit loans[/url] and other financial keywords.
My web page is www.usainstantpayday.com

If your page is important contact me.
please only good pages, wih PR>2 and related to financial keywords
Thanks
tisyMometem

Anonymous said...

fox news acorn megan kelley, [url=http://discuss.tigweb.org/thread/187756]sex megan fox[/url] megaan fox
kim kardashian showing skin, [url=http://discuss.tigweb.org/thread/187768]kim kardashian diet[/url] kim kardashian best booty pics
taylor swift crazier lyrics, [url=http://discuss.tigweb.org/thread/187772]taylor swift dresses[/url] youtube taylor swift love story
hannah montana coat, [url=http://discuss.tigweb.org/thread/187786]hannah montana wallpaper for free for computer[/url] lyrics to nobodys perfect by hannah montana
madam pomfree harry potter, [url=http://discuss.tigweb.org/thread/187792]harry potter books in order[/url] universal orlando harry potter
celebrity naked tom cruise, [url=http://discuss.tigweb.org/thread/187798]cruise charleston to jacksonville[/url] cruises to america and canada
justin bieber youtube, [url=http://discuss.tigweb.org/thread/187812]justin beiber down to earth[/url] is justin bieber and selena gomez
britney spears on talk shows, [url=http://discuss.tigweb.org/thread/187814]britney spears statistics[/url] britney spears concert
megan fox shirtless, [url=http://discuss.tigweb.org/thread/175542]horny megan fox pictures[/url] megan fox poster

Anonymous said...

A New York escort girl is not just physically very much charming and sexy; she is also the proud owner of some of the finest qualities like hospitality, innocence and submissive.
Also, Escort girls New York are now available for incall and outcall services for almost all the New York locations.
Payment for your girl can be done online instantly. So, you should not have any sort of issue regarding anything.
Most people always associate intimacy and fantasy with escorts. Yes, these are very important part of the escort services. But with time these services have evolved and now they try to fulfill all the desires of the clients, whether it is physical desires or psychological desires like companionship and friendship. If you want, you can have a complete date like experience with an escort.
[url=http://bijouescorts.com]Escort NYC[/url] The growing popularity of a New York escort agency has been the outcome of a number of factors. First, a New York based escort agency believes in offering only the most exciting range of escort fun. Secondly, the rates that such an escort agency charges always comes under one's budget. Thirdly, instant access of girls in and around New York has been another major contributing factor in its success.

Some agencies also offer the service of having the escorts for a longer period. For this, customers need to pay more and enjoy a pleasant holiday tour with the escort.
To book for the most desiring lady of your choice, search online for the various websites offering the adult entertainment company presenting a brief profile of the ladies in their gallery along with snapshots of them. The booking process is very easy and user friendly with many viable payment options available. You will get the list of services offered by the agency and all you need to do is choose the one that matches your requirements.
http://bijouescorts.com New York escorts are genuinely the best girlfriends for men seeking for pleasure. They are the abode of beauty and charm and satisfy men with their amazing sense of maturity. The top-quality escorts of New York are the finest and greatly enviable attractive girls who understand the need and desire of their customer. They are blessed with the most alluring bodies and with the superior set of soft skills; they can make anyone feel special.