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.

15 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...

piracy affects porn but it's still winner during the crunch


----------------
kelly divine

Anonymous said...

[url=http://cpcheat.org/]Club Penguin Cheats[/url] gives you a [url=http://cpcheat.org/club-penguin-money-maker/]Club Penguin Money Maker[/url] that permits you to make a lot of coins in Club Penguin.
[url=http://cpcheat.org/]Club Penguin Codes[/url] also provides you with [url=http://cpcheat.org/club-penguin-trackers/]Club Penguin Trackers[/url] such as a [url=http://cpcheat.org/club-penguin-aunt-arctic-tracker/]Club Penguin Aunt Arctic Tracker[/url], a [url=http://cpcheat.org/club-penguin-cadence-tracker/]Club Penguin Cadence Tracker[/url], a [url=http://cpcheat.org/club-penguin-gary-tracker/]Club Penguin Gary Tracker[/url], a [url=http://cpcheat.org/club-penguin-band-tracker/]Club Penguin Band Tracker[/url], a [url=http://cpcheat.org/club-penguin-rockhopper-tracker/]Club Penguin Rockhopper Tracker[/url], and a [url=http://cpcheat.org/club-penguin-sensei-tracker/]Club Penguin Sensei Tracker[/url].
Last,[url=http://cpcheat.org/]Club Penguin Cheats[/url] provides you with [url=http://cpcheat.org/club-penguin-bots/]Club Penguin Bots[/url] and [url=http://cpcheat.org/]Club Penguin Mission Cheats[/url] and [url=http://cpcheat.org/]Club Penguin Coin Cheats[/url]

Anonymous said...

looking for ed drugs? [url=http://www.cahv.org]buy viagra online [/url]and charge out of sprung shipping at http://www.cahv.org . another good place to [url=http://www.kiosknews.org]buy viagra online[/url] is www.kiosknews.org .

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...

Hi guys,

I know this might be a bit off topic but seeing that a bunch of you own websites, where would the best place be to host. Someone recommended I use [url=http://bit.ly/aTAtZb]Blue Host[//url] for $6.95 a month which seems like a great deal. Anyone here on www.blogger.com using them?

Anonymous said...

I just discovered [url=http://bit.ly/bMGrYw]SatelliteTV[/url] on my PC! Ultra cheap at only $50 once off to get the software and an account on the Internet. I get more channels(in HD I might ad) than I get on cable so tomorrow I reckon I'm going to cancel my cable subscription. Thought I'd share this with you guys, worth to check out.

Anonymous said...

The French gourmet cheese Bleu d'Auvergne has a wonderful aroma, a rich taste; the saltiness increases with the incidence of veining. The overall flavor is piquant but not overly sharp. Bleu d'Auvergne started life as an imitation of Roquefort, using cow's milk in place of sheep's milk. Legend has it that a peasant, around 1845, decided to inject his cheese with a blue mold that he found growing on his left-over bread (the motto being, waste not, want not). And thus, the gourmet cheese Bleu d'Auvergne was born. This French gourmet blue cheese comes from the region of Auvergne and the cheese is made from milk of Salers and Aubrac cows. The rind is very thin and so the cheese is usually wrapped in foil. The cheese is rich and creamy with a pale yellow color and scattered holes and well-defined greenish-blue veining. We cut and wrap this cheese in wedge of 8 ounces and 1 pound.

buy fresh blue cheese

[url=http://riderx.info/members/buy_5F00_fresh_5F00_blue_5F00_cheese.aspx]buy fresh blue cheese[/url]

http://riderx.info/members/buy_5F00_fresh_5F00_blue_5F00_cheese.aspx

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.

Anonymous said...

Greetings

I just wanted to say hi to everyone

See you

[URL=http://www.vpnclient.us][IMG]http://openvpn.net/archive/openvpn-users/2005-05/pngd55nFojmJX.png[/IMG][/URL]

Anonymous said...

Greetings

I just wanted to say hi to everyone

Adios

[URL=http://www.vpnmaster.com][IMG]http://openvpn.net/archive/openvpn-users/2005-05/pngd55nFojmJX.png[/IMG][/URL]