繁体   English   中英

打印排序的树图(根据值排序)

[英]Printing a sorted treemap(sorted based on values)

我已经根据值对TreeMap进行了排序,并按如下所示进行打印:

abortion-2
able-2
ab-2
aaron-2
aaa-2
aa-2
a-2
absent-1
absence-1
abraham-1
ability-1
aberdeen-1
abc-1

但是似乎具有相同值的单词以相反的顺序打印:

“人工流产,能干,ab,亚伦,aaa,aa,a”代替“ a,aa,aaa,aaron,ab,能流产”等等。

我什至考虑过将具有相同值的每组键添加到TreeSet并打印出来,但是我无法根据下一个值对其进行迭代。

这是我要传递给TreeMap的比较器。 有人可以帮助我更正代码以按正确的顺序打印吗?

 public class MyComparator implements Comparator<String>{
    Map<String, Integer> tiedMap; 

    public MyComparator(Map<String, Integer> map){
       this.tiedMap = map; 
    }        

    public int compare(String a, String b){
        if(tiedMap.get(a)>=tiedMap.get(b)){
            return -1;
        }
        else
            return 1;
    }
}

这是我尝试打印的方式:

Iterator it = tree.entrySet().iterator();
for(int i=0; i<n; i++){
   if(it.hasNext()){
      Map.Entry pairs = (Map.Entry)it.next();
      System.out.println(pairs.getKey()+"-"+pairs.getValue());
   }
}

编辑:我正在将输入读取到TreeMap中,然后将其传递给另一个TreeMap。

编辑:创建TreeMaps的代码:

Map<String, Integer> map = new TreeMap<String, Integer>();        
Words t = new Words();         
MyComparator comp = w.(new MyComparator(map));       
Map<String, Integer> tree = new TreeMap<String, Integer>(comp); 

int size = Integer.parseInt(buffer.readLine());
   for(int i = size; i>0; i--){
       reader = buffer.readLine();
       if(map.get(reader)!=null){
          map.put(reader, map.get(reader)+1);
       }
       else
          map.put(reader, 1);                
   }
tree.putAll(map);      
if(tiedMap.get(a)>=tiedMap.get(b)){
    return -1;
}
else
    return 1;

您应该修改代码以在值相同时返回0。 这将确保原始密钥之间的相对顺序不变。 如果这样不起作用,则可以添加其他代码,例如:

if (tiedMap.get(a) == tiedMap.get(b))
  return a.compareTo(b);

比较器将仅根据其值返回以相反顺序排序的条目。 这是你想要的吗?

另外,如果您希望输入的顺序更可预测,则还应该比较以下项:

public int compare(String a, String b)
{
    Integer aVal = tiedMap.get(a);
    Integer bVal = tiedMap.get(b);

    if (aVal > bVal)
    {
        return 1; // or -1 for descending order
    }
    else if (aVal < bVal)
    {
        return -1; // or 1 for descending order
    }
    else
    {
        // if values are equivalent compare on key as well
        return a.compareTo(b);
        // or for descending order:
        // return b.compareTo(a);
    }
}

实际上,通过使用比较器,您可以将HashMap, TreeMap排序为升序和降序。

试试这个:

// sort list based on comparator
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o2)).getValue())
                                   .compareTo(((Map.Entry) (o1)).getValue());
        }
    });

这将使输出降序排列。 通过仅interchanging the o2 and o1 only ,您将使它们按升序排序。

我不确定我是否完全理解您的期望/实现,但是我认为您需要在比较函数中的字符串a和b之间进行字符到字符的比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM