views:

724

answers:

7

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

+1  A: 

Provide it a Comparator that compares strings case ignored.

TreeMap(Comparator c)

Murali VP
A: 

If you had a list, I would say try Collections.sort() with a Comparator. You may have to roll your own Comparator that uses String.equalsIgnoreCase() instead of equals().

public static <T> void sort(List<T> list,
                        Comparator<? super T> c)

But I was on the right track. Try the TreeMap constructor that takes a Comparator:

public TreeMap(Comparator<? super K> comparator)
shoover
+3  A: 

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)
Chi
A: 

Yes, what you want is to use the TreeMap constructor that takes a Comparator. Make a comparator that uses compareToIgnoreCase.

dustmachine
A: 

I suspect that you should construct your TreeMap with a custom comparator.

import java.text.Collator; import java.util.Comparator;

class IgnoreCaseComp implements Comparator { Collator col;

IgnoreCaseComp() { col = Collator.getInstance();

col.setStrength(Collator.PRIMARY);

}

public int compare(String strA, String strB) { return col.compare(strA, strB); } }

Jeff Paquette
+10  A: 

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.

Michael Brewer-Davis
+1 for the link to `String.CASE_INSENSITIVE_ORDER`.
tangens
A: 

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

You should be able to use a BeanComparator.

camickr
I've recommended the question be reverted to the original question and a new question posted instead; if and when that happens, this answer ought probably to be removed too.
Kevin Bourrillion