How to count text file character frequencies in Java

1 Answer

0 votes
package javaapplication1;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class JavaApplication1 {

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

        try {

            HashMap<Integer, Integer> hash = new HashMap<>();

            try (BufferedReader reader = new BufferedReader(new FileReader("d:\\data.txt"))) {
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    for (int i = 0; i < line.length(); i++) {
                        char ch = line.charAt(i);
                        if (ch != ' ') {
                            int n = hash.getOrDefault((int) ch, 0);
                            hash.put((int) ch, n + 1);
                        }
                    }
                }
            }

            for (int key : hash.keySet()) {
                System.out.println((char) key + " - " + hash.get(key));
            }

        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}


/*
                   
run:

a - 4
c - 4
# - 1
h - 2
i - 1
j - 2
+ - 2
n - 1
o - 1
p - 4
r - 1
s - 1
t - 2
v - 2
y - 1
          
*/

 



answered Dec 18, 2016 by avibootz

Related questions

1 answer 168 views
1 answer 159 views
1 answer 188 views
1 answer 184 views
1 answer 169 views
1 answer 189 views
1 answer 214 views
...