Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collator plus Comparator

I have a collection of beans OptionItemDTO (properties label and value) and I'm currently using something like this to sort by label:

Collections.sort(combo, new LabelComparator())

The problem is that it does not sort stressed vowels (my locale is spanish).

According to this document http://blogs.oracle.com/CoreJavaTechTips/entry/sorting_strings I must use a Collator class.

But if I use the sort with collator, I can't use the comparator (and vice-versa). Any ideas?

Thanks in advance!

like image 840
Lluis Martinez Avatar asked Nov 30 '11 16:11

Lluis Martinez


2 Answers

Your LabelComparator should delegate to a Collator to compare the labels of your DTOs:

public int compare(OptionItemDTO dto1, OptionItemDTO dto2) {
    return collator.compare(dto1.getLabel(), dto2.getLabel());
}
like image 172
JB Nizet Avatar answered Sep 22 '22 20:09

JB Nizet


I have written a small framework to sort collections of objects with CollationKeys (rather than Collators):

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/text/Localizables.html

You just have to implement a Localizer (or make your POJO implement Localizable) to provide a string representation:

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/text/Localizer.html

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/text/Localizable.html

You can have a look at the unit tests for some samples:

http://softsmithy.hg.sourceforge.net/hgweb/softsmithy/lib/main-golden/file/5c4db802573b/lib-core/src/test/java/org/softsmithy/lib/text/LocalizablesTest.java

The library is open source.

https://sourceforge.net/projects/softsmithy/files/softsmithy/v0.1/

<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>lib-core</artifactId>  
    <version>0.1</version>  
</dependency>  
like image 24
Puce Avatar answered Sep 19 '22 20:09

Puce