Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Map<String, Object> by keys with IgnoreCase?

Well, I tested TreeMap but it doesn't take in account IgnoreCase on string comparision. I need to order lexicographically and ignoring case. Is there any other way?

Thanks, that works (TreeMap (Comparator c)). However, I have another question:

public final Comparator<Object> STR_IGN_CASE_COMP = new Comparator<Object>() {

    public int compare(Object h1, Object h2) {
            String s1 = h1.getId();
            String s2 = h2.getId();
            return s1.compareToIgnoreCase(s2);
    }
}; //STR_IGN_CASE_COMP

How can I universialize the comparator to work with different objects? assuming all have the getId() method.

Thanks, Martin

like image 319
d0pe Avatar asked Nov 07 '09 01:11

d0pe


1 Answers

The best way would be to use a Collator. A collator is a built in class, which also implements Comparable, and therefore you can use it for your TreeMap.

With a collator, you can also control the strength of the comparision, for example, if you want to be accent-insensitive as well.

Collator stringCollator = Collator.getInstance();
stringCollator.setStrength(Collator.PRIMARY); 
new TreeMap<String, String>(stringCollator)
like image 92
Chi Avatar answered Oct 17 '22 18:10

Chi