计算文件JAVA中的相同行 [英] Count same lines in a file, JAVA

查看:62
本文介绍了计算文件JAVA中的相同行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含动物行,该动物行在此列表中出现1到n次.我需要阅读此文本文件,对所有单独的动物发生次数进行计数,将它们从最高到最低排序,然后将它们放入jtable.

I have a text file which has lines of animals, who occur on this list from 1 to n times. I need to read this text file, count all the separate animal occurences, sort them from highest to lowest and put them in a jtable.

例如,文本文件如下所示:

For example, the text file looks like this:

dog
sheep
cat
horse
cat
tiger
cat
cat
tiger

我需要像这样计算所有相同的发生次数:

I need to count all the same occurences like so:

dog 1
sheep 1
cat 4
horse 1
tiger 2

然后将它们从最高到最低排序,并以某种方式将它们放入表格中,这样就可以了:

And then sort them from highest to lowest and somehow put them into a table, so that would be:

Animal name: count
cat          4
tiger        2
dog          1
sheep        1
horse        1

所以,现在我的具体问题是如何计算所有单独动物的比赛次数?

So, for now my specific question is how can i count the matches for all the separate animals?

感谢您的帮助!

维沙尔·卡马特(Vishal Kamat)提供的答案行之有效,我的动物及其发生的次数已通过以下代码进行计数:

The answer provided by Vishal Kamat, has worked, my animals and their occurences have been counted with this code:

来自文本文件的Java hashmap字数

现在,我只需要将所有这些信息放到一个新的jtable中

Now, I just need to put all this information to a new jtable

推荐答案

只需使用开关盒即可.您可以为每只动物使用一个计数器.或使用arrayList在其中可以存储每种动物的数量...

Just use the switch-case. You can use a counter for each animal. Or use an arrayList where you can store the amount of each animal...

   String line = reader.readLine();
        while (line != null) {
            switch (line) {
                case "cat":
                catCounter++;
                break;
                case "dog":
                dogCounter++;
                break;
                case "horse":
                horseCounter++;
                break;
                case "tiger":
                tigerCounter++;
                break;
                case "sheep":
                sheepCounter++;
                break;
                default:
                break;
            }
        }

这篇关于计算文件JAVA中的相同行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆