Reputation: 583
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
Upvotes: 10
Views: 11442
Reputation: 7127
I suspect that you should construct your TreeMap
with a custom comparator.
import java.text.Collator;
import java.util.Comparator;
class IgnoreCaseComp implements Comparator<String> {
Collator col;
IgnoreCaseComp() {
col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
}
public int compare(String strA, String strB) {
return col.compare(strA, strB);
}
}
Upvotes: 0
Reputation: 324147
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.
Upvotes: 1
Reputation: 14276
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.
Upvotes: 37
Reputation: 10824
Yes, what you want is to use the TreeMap constructor that takes a Comparator. Make a comparator that uses compareToIgnoreCase.
Upvotes: 0
Reputation: 23174
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)
Upvotes: 8
Reputation: 3140
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)
Upvotes: 0
Reputation: 6427
Provide it a Comparator that compares strings case ignored.
TreeMap(Comparator c)
Upvotes: 1