如何按降序按频率对列表进行排序

时间:2015-08-31 21:56:49

标签: java sorting hashmap

我已经完成了我的代码,在搜索后多次查找前20个单词,但它不是在降序单词中。 如果两个单词的帐号相同,我需要添加代码按频率按降序排序列表:

{'cat'=> 43,'c'=> 43}

输出应为

C

我的代码是:

 public static void main(String[] args) throws IOException{

            String delimiters = ".;_?>*/";

            String[] result = new String[20];
            List<String> listArray = new ArrayList<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            FileReader fileR = new FileReader("D:/test.txt");
            BufferedReader bufferedR = new BufferedReader(in);
            String line;

            while ((line = bufferedR.readLine()) != null) {
                    StringTokenizer sToken = new StringTokenizer(line, delimiters);
                    while (sToken.hasMoreTokens()) {
                        String token = sToken.nextToken().trim().toLowerCase();
                                    if (map.containsKey(token)) {
                                        int val =  map.get(token);
                                        val++;
                                        map.put(token, val);



                                    } else{
                                        map.put(token, 1);

                                    }                       
               }  
            }
            bufferedR.close();
            for(int i=0;i<result.length;i++){
                int mValu=0;
                String wKey="";
                for(Map.Entry<String,Integer> entry:map.entrySet()){
                    if(entry.getValue()>mValu){
                        mValue=entry.getValue();
                        wKey=entry.getKey();
                    }
                }
                map.remove(wKey);
                result[i]=wKey;

            }
            for (int i = 0 ; i<result.length;i++){
                System.out.println(result[i]);

        }
        }
    }

当我研究这个主题时,我发现了这段代码,但不知道它是如何适合我的代码的:

 List<Map.Entry<String, Integer>> entries = new `ArrayList`<Map.Entry<String, Integer>>(map.entrySet());
    Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
            return Integer.compare(b.getValue(), a.getValue());
        }
    });

或者更好地了解如何按降序获得频率?!

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

create table Divisions(StoreId int)
insert into Divisions values (1), (2), (3)

declare @items table(ItemID int)
insert into @items values (5), (6), (7)

-- insert into target(stireid, itemid, otherColumn)
select d.StoreId, i.ItemID, 27
from Divisions d 
cross join @items i

答案 1 :(得分:0)

您需要做的是对地图进行排序。根据我的理解,你想要前20个值,如果两个值具有相同的标记,那么它应该按字典顺序排列。

我的解决方案是首先按键(您的情况下为令牌)和然后按值排序您的地图。

这样,令牌的排序顺序将保持不变,地图顺序将按您希望输出的方式进行。

<强>小心 确保您使用的排序算法是一个就地排序算法,如Quicksort,否则上述解决方案将无效。

相关问题