我有一个HashMap需要按降序排序,而不是按键排序。为了获得hashmap,我确定给定的输入行是否是sql语句,找到它的复杂性,然后创建一个hashmap,其中key作为sql语句,value作为复杂性。虽然我已经编写了正确的代码,但我认为,要对HashMap进行排序,输出不会显示已排序的hashmap。这是代码:
ion-badge {justify-content: center; }
}
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();
在这里输入代码
答案 0 :(得分:0)
每次创建一个新地图,在循环中有一个条目,对其进行排序并打印。在循环外移动地图内容的排序和打印。
while (sc.hasNextLine()) {
//construct the map
}
Map<String, Integer> sorted_map = sqlf.sortByValue(map1);
sqlf.printMap(sorted_map);