从文本文件中计算java hashmap字数 [英] java hashmap word count from a text file

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

问题描述

我试图从文本文件中读取信息,我需要找出每个单词由空格分隔的次数。然后我需要按字母顺序输出每个单词的计数。我正在寻找使用TreeMap,keySet()和迭代器。我的代码非常不完整,我很困难。

I am trying to code to read info from a text file, I need to find out how many times each word separated by white space occurs. I then need to output in alphabetical order with the count of each word. I am looking to use a TreeMap, keySet() and an Iterator. My code is very incomplete and I am quite stuck.

    import java.util.HashMap;
    import java.util.Map

    public class WordCount<E extends Comparable<E>> {

        private static Map<String, Integer> map = new HashMap<String, Integer>();

        static {
            fillMap(map, "Alice.txt");
        }

        private static void fillMap(Map<String, Integer> map, String fileName) {


       }

}

推荐答案

您要求的确切代码。它会保存每一个字并统计它们。如果它获得的单词不存在,它将把它添加到Map中,如果它确实存在,它将增加它的值。最后,它将打印所有的键和值。
使用它,如果您有任何问题,请询问。

This is the exact code that you asked for. It will Save every Word and count them. if the word it gets didn't exist, it will add it to the Map, if it did, it will increase its value. At the end, it will print all keys and values. use it, if you got any question, ask.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/*
 * @author Mr__Hamid
 */
public class overFlow {

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

        Map m1 = new HashMap();

        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                String[] words = line.split(" ");//those are your words
                for (int i = 0; i < words.length; i++) {
                    if (m1.get(words[i]) == null) {
                        m1.put(words[i], 1);
                    } else {
                        int newValue = Integer.valueOf(String.valueOf(m1.get(words[i])));
                        newValue++;
                        m1.put(words[i], newValue);
                    }
                }
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
        }
        Map<String, String> sorted = new TreeMap<String, String>(m1);
        for (Object key : sorted.keySet()) {
            System.out.println("Word: " + key + "\tCounts: " + m1.get(key));
        }
    }
}

这篇关于从文本文件中计算java hashmap字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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