Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

java hashmap word count from a text file

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) {


       }

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 + "	Counts: " + m1.get(key));
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...