Java 将HashMap排序到TreeMap中:自定义比较器删除具有相同键的值
我正在尝试对哈希映射进行排序。我有以下用于排序的代码:Java 将HashMap排序到TreeMap中:自定义比较器删除具有相同键的值,java,hashmap,comparator,Java,Hashmap,Comparator,我正在尝试对哈希映射进行排序。我有以下用于排序的代码: private static class ValueComparator implements Comparator<String>{ HashMap<String, Long> map = new HashMap<String, Long>(); public ValueComparator(HashMap<String, Long> map
private static class ValueComparator implements Comparator<String>{
HashMap<String, Long> map = new HashMap<String, Long>();
public ValueComparator(HashMap<String, Long> map){
this.map.putAll(map);
}
@Override
public int compare(String s1, String s2) {
if(map.get(s1) > map.get(s2)){
System.out.println("s1: " + s1 + "; s2: " + s2);
return -1;
}
else if (map.get(s1).equals(map.get(s2))) {
return 0;
}
else{
return 1;
}
}
}
private static TreeMap<String, Long> sortMapByValue(HashMap<String, Long> map){
Comparator<String> comparator = new ValueComparator(map);
//TreeMap is a map sorted by its keys.
//The comparator is used to sort the TreeMap by keys.
TreeMap<String, Long> result = new TreeMap<String, Long>(comparator);
result.putAll(map);
System.out.println("DONE sort");
return result;
}
私有静态类ValueComparator实现Comparator{
HashMap=newHashMap();
公共价值比较器(HashMap){
this.map.putAll(map);
}
@凌驾
公共整数比较(字符串s1、字符串s2){
if(map.get(s1)>map.get(s2)){
系统输出打印项次(“s1:+s1+”;s2:+s2);
返回-1;
}
else if(map.get(s1).equals(map.get(s2))){
返回0;
}
否则{
返回1;
}
}
}
私有静态树映射sortMapByValue(HashMap映射){
比较器比较器=新值比较器(map);
//TreeMap是按其键排序的贴图。
//比较器用于按键对树映射进行排序。
TreeMap结果=新的TreeMap(比较器);
结果:putAll(map);
System.out.println(“完成排序”);
返回结果;
}
问题是,当几个不同的键具有相同的值时,只有一个键进入最终贴图:
示例:
public class Test {
public static void main(String[] args) {
HashMap<String, Long> hashMap = new HashMap<>();
hashMap.put("Cat", (long) 4);
hashMap.put("Human", (long) 2);
hashMap.put("Dog", (long) 4);
hashMap.put("Fish", (long) 0);
hashMap.put("Tree", (long) 1);
hashMap.put("Three-legged-human", (long) 3);
hashMap.put("Monkey", (long) 2);
System.out.println(hashMap); //7 pairs
System.out.println(sortMapByValue(hashMap)); //5 pairs
}
}
公共类测试{
公共静态void main(字符串[]args){
HashMap HashMap=新的HashMap();
hashMap.put(“Cat”,(long)4);
hashMap.put(“人”(long)2);
hashMap.put(“Dog”(长)4);
hashMap.put(“Fish”,(long)0);
hashMap.put(“树”,长)1);
hashMap.put(“三条腿的人”(long)3);
hashMap.put(“Monkey”,(long)2);
System.out.println(hashMap);//7对
System.out.println(sortMapByValue(hashMap));//5对
}
}
我该如何修复它呢?我认为它是不可修复的,因为你在无意中使用地图,并且违反了合同。树映射应按键排序,键应唯一,因此当compare==0时,它将覆盖节点的值。您始终可以实现自己的树映射,并让它做任何您想做的事情 我不知道你想用它做什么,但我想你需要像这样的东西
TreeMap<Long,List<String>>
TreeMap
if(cpr!=null){
做{
父代=t;
cmp=心肺复苏比较(键,t键);
if(cmp<0)
t=t左;
否则如果(cmp>0)
t=t右;
其他的
返回t.setValue(值);
}而(t!=null);
我认为这是不可修复的,因为您无意中使用了映射并破坏了契约。树映射预期按键排序,并且键预期是唯一的,因此当compare==0时,它将覆盖节点的值。您可以始终实现自己的树映射,并让它执行任何您想要的操作
我不知道你想用它做什么,但我想你需要像这样的东西
TreeMap<Long,List<String>>
TreeMap
if(cpr!=null){
做{
父代=t;
cmp=心肺复苏比较(键,t键);
if(cmp<0)
t=t左;
否则如果(cmp>0)
t=t右;
其他的
返回t.setValue(值);
}而(t!=null);