排序映射<字符串 ,对象>通过带有 IgnoreCase 的键?字符串>
好吧,我测试了 TreeMap,但它没有考虑字符串比较中的 IgnoreCase。我需要按字典顺序排序并忽略大小写。还有其他办法吗?
谢谢,这有效(TreeMap(比较器 c))。但是,我还有另一个问题:
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
如何通用比较器以处理不同的对象?假设都有 getId() 方法。
谢谢, 马丁
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我怀疑您应该使用自定义比较器构建您的
TreeMap
。I suspect that you should construct your
TreeMap
with a custom comparator.您想要使用
Comparator
在TreeMap
构造函数。特别是,请查看String.CASE_INSENSITIVE_ORDER
。使用
Collator
或者,在非英语语言环境中或如果您需要更复杂的排序,自定义Comparator
可能会更适合您。You want to use a
Comparator
in theTreeMap
constructor. In particular, look atString.CASE_INSENSITIVE_ORDER
.Using
Collator
or a customComparator
may work better for you in a non-English locale or if you need more complex ordering.最好的方法是使用 Collator。 Collator 是一个内置类,它也实现了 Comparable,因此您可以将它用于 TreeMap。
使用整理器,您还可以控制比较的强度,例如,如果您也想不区分重音。
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.
为其提供一个比较器,用于比较忽略大小写的字符串。
树形图(比较器 c)
Provide it a Comparator that compares strings case ignored.
TreeMap(Comparator c)
您应该能够使用 BeanComparator。
You should be able to use a BeanComparator.
如果你有一个列表,我会说尝试带有比较器的 Collections.sort() 。您可能必须推出自己的使用 String.equalsIgnoreCase() 而不是 equals() 的比较器。
但我走在正确的轨道上。尝试使用 Comparator 的 TreeMap 构造函数:
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().
But I was on the right track. Try the TreeMap constructor that takes a Comparator:
是的,您想要的是使用带有 Comparator 的 TreeMap 构造函数。创建一个使用compareToIgnoreCase的比较器。
Yes, what you want is to use the TreeMap constructor that takes a Comparator. Make a comparator that uses compareToIgnoreCase.