java - 按单词出现的降序显示

标签 java find-occurrences

我必须计算单词的出现次数并按出现次数(按降序)显示它们。我可以数出单词数,但不知道如何继续。可能是我做事效率不高。如果可能,请提出解决方案。

import java.io.*;
import java.util.*;

public class MaxOccurence
{
    public static void main(String[] args)
    {
        Map<String, Integer> map = new HashMap<>();
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(new File(
                "F:/Demo/file_reading/bin/demo/hello.txt")));
            String str;
            while ((str = br.readLine()) != null)
            {
                Scanner sc = new Scanner(str);
                while (sc.hasNext())
                {
                    String word = sc.next();
                    if (map.containsKey(word))
                        map.put(word, map.get(word) + 1);
                    else
                        map.put(word, 1);
                }
            }
            System.out.println("yes");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        System.out.println(map);
    }
}

最佳答案

我认为您使用 HashMap 类和 map.containsKey 方法的方法对于您解决的字数统计是一种有效的方法,所以剩下的就是排序和打印 map 按降序排列,这里是一个关于如何实现此目的的干净而有效的示例:

map.entrySet().stream()
          .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
          .forEachOrdered(System.out::println);

请注意,如果删除 Collection.reverseOrder 调用,则顺序将为升序。

将其添加到您的代码中将如下所示:

import java.io.*;
import java.util.*;
import java.util.stream.*;

public class MaxOccurence {

  public static void main(String[] args) {

    Map<String, Integer> map = new HashMap<>();
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(
                "F:/Demo/file_reading/bin/demo/hello.txt")));
        String str;
        while ((str = br.readLine()) != null) {
            Scanner sc = new Scanner(str);
            while (sc.hasNext()) {
                String word = sc.next();
                if (map.containsKey(word))
                    map.put(word, map.get(word) + 1);
                else
                    map.put(word, 1);
            }
        }
        System.out.println("yes");
    } catch (IOException e) {
        e.printStackTrace();
    }
    map.entrySet().stream()
              .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
              .forEachOrdered(System.out::println);

  }

}

关于java - 按单词出现的降序显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709986/

相关文章:

SQL查询查找表中出现次数最多的值,无需嵌套

java - 为什么 RMI 注册表需要我的远程接口(interface)类文件?

java - 通过打开/关闭 300 多个复选框来改善用户体验

java - Android AudioRecorder 对象不会从麦克风读取

java - 尽管通过了测试,但未生成 Pact 文件

SED 替换了一些首次出现(和范围)的模式

c# - 查找数组中最大值的出现

java - 以通用方式重试方法调用

string - Bash:从字符第一次出现到第二次出现的子字符串

python - 访问列表中的重复元素并打印其旁边的元素