Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

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 155 views
1 answer 146 views
1 answer 175 views
1 answer 164 views
1 answer 161 views
1 answer 177 views
1 answer 202 views
...