【发布时间】:2016-11-22 10:23:27
【问题描述】:
我有一个 ImmutableSortedMap,它将数据保存在以下数据结构中。
<String, Pair<Long, Double>>
我的目标是从最大的Double 开始按降序对该地图进行排序,如果两个Doubles 相同,则按Long 对其进行排序。如果Double和Long相同,则按String排序
我目前的比较器只处理第一种情况,看起来像这样。
private ImmutableSortedMap<String, Pair<Long, Double>> sortInDescendingSizeOrder(final Map<String, Pair<Long, Double>> statsByType) {
Ordering<String> ordering = Ordering
.from(new Comparator<Pair<Long, Double>>() {
@Override
public int compare(Pair<Long, Double> o, Pair<Long, Double> o2) {
return o.getRight().equals(o2.getRight()) ? o.getLeft().compareTo(o2.getLeft()) : o.getRight().compareTo(o2.getRight());
}
})
.reverse()
.onResultOf(Functions.forMap(statsByType, null));
return ImmutableSortedMap.copyOf(statsByType, ordering);
}
但是,它找到两个相同的Doubles 并抛出以下异常:Exception in thread "main" java.lang.IllegalArgumentException: Duplicate keys in mappings
我不明白我做错了什么......
编辑:我尝试添加 compound 方法并按字符串排序(至少)。
.compound(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
这使得代码不会抛出任何异常,但是,结果映射中没有任何排序。
编辑 2:在这一点上,任何类似于上述的排序
Map<String, Pair<Long, Double>>
会的。不一定需要是 ImmutableSortedMap
【问题讨论】:
标签: java sorting guava comparator