【问题标题】:HashMap not getting sorted by valueHashMap 未按值排序
【发布时间】:2026-02-12 05:40:01
【问题描述】:

我有一个 HashMap,它需要按值而不是键按降序排序。为了得到 hashmap,我确定给定的输入行是否是一个 sql 语句,找到它的复杂性,然后创建一个 hashmap,其中 key 作为 sql 语句, value 作为复杂性。尽管我编写了正确的代码来对 HashMap 进行排序,但输出并未显示已排序的 hashmap。代码如下:

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
    @Override
    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
        return (o1.getValue()).compareTo(o2.getValue());
    }
});

Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
    result.put(entry.getKey(), entry.getValue());
}
return result;

}

public void method2() throws Exception{


try (FileInputStream inputStream = new FileInputStream(fileName);
        Scanner sc = new Scanner(inputStream, "UTF-8")){

        while (sc.hasNextLine()) {
            String line = sc.nextLine();
           // System.out.println("THIS IS METHOD 2 EXECUTING");
            SQLChecker checker = new RegexSQLChecker();

            if(checker.isSQLStatement(line)){
                SQLFreq sqlf=new PrintFreqMap();
              //Trim the line to start with a SQL keyword
            String line1=   sqlf.trimString(line);

                 //*******FIND_QUERY_COMPLEXITY*******

                ComplexityScore cs=new ComplexityScorer();

                   int complexity= cs.findComplexity(line1);
                  map1 = new HashMap<String, Integer>();
                  map1.put(line1,complexity);
                  Map<String, Integer> sorted_map4 = sqlf.sortByValue(map1);


                  if(outputFormat.equals("txt"))
                  o.writeMapToTextFile(map1, p2);
                  if(outputFormat.equals("csv"))
                  o.writeHashMapToCsv(map1,p5);
                  sqlf.printMap(sorted_map4);
                  if(outputFormat.equals("html"))
                        o.writeMapToHTML(sorted_map4,p7); 

            }


        }
        //SQLFreq sqlf=new PrintFreqMap();

}

}


public void printMap(Map<String, Integer> map)
{
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println("Key :" + entry.getKey() + " Value : "
            + entry.getValue());
    }
}

在此处输入代码

【问题讨论】:

标签: java hashmap linkedhashmap


【解决方案1】:

您每次都在循环中创建一个新地图,对其进行排序和打印。将地图内容的排序和打印移到循环之外。

while (sc.hasNextLine()) {
   //construct the map
}
Map<String, Integer> sorted_map = sqlf.sortByValue(map1);
sqlf.printMap(sorted_map);

【讨论】:

  • 这只会打印地图的最后一个条目
  • @Apoorva 并将 map1 = new HashMap&lt;String, Integer&gt;(); 移动到循环之前。