[英]Comparator creates duplicates in TreeMap
I would like to sort my HashMap
(or TreeMap
) by values. 我想按值对我的HashMap
(或TreeMap
)进行排序。 I kind of achieved this by creating a custom Comparator
that sorts after value. 我通过创建一个按值排序的自定义Comparator
来实现这一点。 However whenever I put in all my entries from the HashMap
again I get duplicates. 但是,每当我再次从HashMap
输入所有条目时,都会得到重复。
How can I sort by values without creating duplicates? 如何按值排序而不创建重复项?
CODE 码
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
ValueComparator vc = new ValueComparator(hMap);
TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(vc);
hMap.put(0, "b");
hMap.put(1, "c");
hMap.put(2, "a");
tMap.putAll(hMap);
tMap.putAll(hMap);
for (Map.Entry<Integer, String> entry : tMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
class ValueComparator implements Comparator<Integer> {
Map<Integer, String> base;
public ValueComparator(Map<Integer, String> base) {
this.base = base;
}
public int compare(Integer a, Integer b) {
if (base.get(a).charAt(0) >= base.get(b).charAt(0))
return 1;
else return -1;
}
}
OUTPUT OUTPUT
2 a
2 a
0 b
0 b
1 c
1 c
The compare
method should return 0
if both objects are equal. 如果两个对象相等,则compare
方法应返回0
。 In your implementation, you're returning 1
, and thus the map does not recognize duplicates properly. 在您的实现中,您将返回1
,因此映射无法正确识别重复项。
One way to solve this is to reuse Character.compare
to compare two char
s: 解决此问题的一种方法是重用Character.compare
比较两个char
:
public int compare(Integer a, Integer b) {
return Character.compare
(base.get(a).charAt(0), base.get(b).charAt(0));
}
You need to modify logic as below, handle all three cases of -1, 0 and 1
您需要按如下所示修改逻辑,处理-1, 0 and 1
所有三种情况
public int compare(Integer a, Integer b) {
if (base.get(a).charAt(0) == base.get(b).charAt(0))
return 0;
else if (base.get(a).charAt(0) > base.get(b).charAt(0))
return 1;
else
return -1;
}
output 产量
2 a
0 b
1 c
Your comparator contract is wrong. 您的比较者合同错误。 the compare method contract says: 比较方法合同说:
Compares its two arguments for order. 比较其两个参数的顺序。 Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. 当第一个参数小于,等于或大于第二个参数时,返回负整数,零或正整数。
Your code is only doing 1 and -1 what about the 0? 您的代码仅执行1和-1,那么0呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.