Java HashMap未按值排序

Java HashMap未按值排序,java,hashmap,linkedhashmap,Java,Hashmap,Linkedhashmap,我有一个HashMap,它需要按值而不是键按降序排序。为了获得hashmap,我确定给定的输入行是否是一个sql语句,找到它的复杂性,然后创建一个hashmap,key作为sql语句,value作为复杂性。虽然我已经编写了正确的代码来对HashMap进行排序,但是输出并没有显示排序后的HashMap。代码如下: public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K,

我有一个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您每次都在创建一个新的映射,循环中有一个条目,对其进行排序并打印。将地图内容的排序和打印移到循环之外

while (sc.hasNextLine()) {
   //construct the map
}
Map<String, Integer> sorted_map = sqlf.sortByValue(map1);
sqlf.printMap(sorted_map);
while(sc.hasNextLine()){
//构建地图
}
Map sorted_Map=sqlf.sortByValue(map1);
sqlf.printMap(排序映射);

此文件的可能副本仅打印文件的最后一个条目map@Apoorva并移动
map1=newhashmap()在循环之前。
}


public void printMap(Map<String, Integer> map)
{
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println("Key :" + entry.getKey() + " Value : "
            + entry.getValue());
    }
}
while (sc.hasNextLine()) {
   //construct the map
}
Map<String, Integer> sorted_map = sqlf.sortByValue(map1);
sqlf.printMap(sorted_map);