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

d0pe picture d0pe · Nov 7, 2009 · Viewed 10.6k times · Source

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

Answer

Michael Brewer-Davis picture Michael Brewer-Davis · Nov 7, 2009

You want to use a Comparator in the TreeMap constructor. In particular, look at String.CASE_INSENSITIVE_ORDER.

TreeMap map = new TreeMap(String.CASE_INSENSITIVE_ORDER);

Using Collator or a custom Comparator may work better for you in a non-English locale or if you need more complex ordering.