fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static void countWords(String text) {
  6. text = text.toLowerCase();
  7. text = text.replaceAll("[^a-zA-Z0-9 ]", "");
  8. String[] words = text.split("\\s+");
  9.  
  10. Map<String, Integer> freq = new HashMap<>();
  11. for (String w : words) {
  12. freq.put(w, freq.getOrDefault(w, 0) + 1);
  13. }
  14.  
  15. for (Map.Entry<String, Integer> e : freq.entrySet()) {
  16. System.out.println(e.getKey() + " → " + e.getValue());
  17. }
  18. }
  19.  
  20. public static void main(String[] args) {
  21. String kalimat = "This is a test. This is only a test";
  22. countWords(kalimat);
  23. }
  24. }
  25.  
Success #stdin #stdout 0.19s 55932KB
stdin
Standard input is empty
stdout
a → 2
test → 2
this → 2
only → 1
is → 2