如何使用基于“外部"的比较器创建 TreeMap价值观 [英] How to create a TreeMap with a comparator based on "external" values
问题描述
我有一个 Map
将字符串的属性映射到一些相关的整数值.
I have a Map<String, Integer> otherMap
which maps properties of strings to some associated integer values.
现在我想要一个 TreeMap
,它根据 otherMap
中的关联整数对键进行排序.
Now I would like a TreeMap<String, String>
that orders the keys according to the associated integers in otherMap
.
我应该如何解决这个问题,需要注意什么?
How should I tackle this problem, and what's important to keep in mind?
(这是对这个问题的跟进.)上>
(This is a follow-up on this question.)
推荐答案
在编写比较器时,重要的是要确保结果一致(即随着时间的推移相同)并且它实现了 总订单.
When writing a comparator it's important to ensure that the results are consistent (i.e. are the same over time) and that it implements a total order.
在 TreeMap
中使用比较器时,还要求它与 equals 一致,这意味着 c.compare(e1, e2)
返回 0
当且仅当 e1.equals(e2)
.
When using the comparator in a TreeMap
it is also required that it is consistent with equals, which means that c.compare(e1, e2)
return 0
if and only if e1.equals(e2)
.
考虑到这一点,可以按如下方式实现正确的比较器:
With this in mind, a correct comparator could be implemented as follows:
class MyComparator implements Comparator<String> {
Map<String, Integer> otherMap;
public MyComparator(Map<String, Integer> otherMap) {
this.otherMap = otherMap;
}
@Override
public int compare(String o1, String o2) {
int primary = otherMap.get(o1).compareTo(otherMap.get(o2));
if (primary != 0)
return primary;
// Fall back on comparing the string keys to ensure consistent results
return o1.compareTo(o2);
}
}
(需要注意的是,otherMap
在传递给 MyComparator
后永远不会改变也是很重要的.)
(It should be noted that it is also important that otherMap
never changes after it is passed to MyComparator
.)
在 Java 8 中,惯用的解决方案看起来像
In Java 8, the idiomatic solution would look like
Comparator.comparing(k -> otherMap.get(k))
.thenComparing(k -> k);
这篇关于如何使用基于“外部"的比较器创建 TreeMap价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!