aspose file tools*
The moose likes Beginning Java and the fly likes Tree Map Sort & foreign languages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Tree Map Sort & foreign languages" Watch "Tree Map Sort & foreign languages" New topic

Tree Map Sort & foreign languages

E Robb
Ranch Hand

Joined: Aug 27, 2010
Posts: 111
I have a tree map that I want to sort on the key. Works fine as long as you use english. When you get into other languages that have accents the sort does not work correctly. In java script there is a call you can use for a more natural search called localeCompare.

Is there a way in java to make a TreeMap have a more natural search?

sortedMap returns btest, ctest, ztest in the correct order. Now if you add a character like optList.put("ét", "1") to the hashmap ét and run it through the tree map it always returns it at the end of the list instead of between ctest & ztest key.

Can a TreeMap do a natural sort that will understand that order of the keys returned should be btest, ctest, ét, ztest?

Paul Clapham

Joined: Oct 14, 2005
Posts: 18165

Yes, because you can create a TreeMap which uses a Comparator which you define.

If you check out the API documentation for Comparator you will see that one of the standard classes which implements it is Collator. So for example if you wanted to collate strings according to the rules for French (as per your example), you could use

to make that happen. Like this:
E Robb
Ranch Hand

Joined: Aug 27, 2010
Posts: 111
Brilliant thank you!
I agree. Here's the link:
subject: Tree Map Sort & foreign languages
Similar Threads
Collections how much detail??
Java Hashmap Sorting
Collections problem
HashMap remove multiple elements
How to keep the order of elements in hashtable