fork download
  1. import java.util.*;
  2.  
  3. class WordCounter {
  4.  
  5. public static Map<String, Integer> countWords(String text) {
  6. Map<String, Integer> countsByNormalized = new HashMap<>();
  7. Map<String, String> displayByNormalized = new HashMap<>();
  8.  
  9. if (text == null || text.isBlank()) {
  10. return Collections.emptyMap();
  11. }
  12.  
  13. String[] tokens = text.split("\\s+");
  14. for (String raw : tokens) {
  15. if (raw == null || raw.isEmpty()) continue;
  16.  
  17. String originalLower = raw.toLowerCase(Locale.ROOT);
  18.  
  19. String normalized = originalLower.replaceAll("^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$", "");
  20.  
  21. if (normalized.isEmpty()) continue;
  22.  
  23. displayByNormalized.putIfAbsent(normalized, originalLower);
  24.  
  25. countsByNormalized.put(normalized, countsByNormalized.getOrDefault(normalized, 0) + 1);
  26. }
  27.  
  28. Map<String, Integer> result = new LinkedHashMap<>();
  29. for (Map.Entry<String, Integer> e : countsByNormalized.entrySet()) {
  30. String normalized = e.getKey();
  31. String display = displayByNormalized.get(normalized);
  32. result.put(display, e.getValue());
  33. }
  34.  
  35. return result;
  36. }
  37.  
  38. public static void printSortedByKey(Map<String,Integer> map) {
  39. map.entrySet().stream()
  40. .sorted(Map.Entry.comparingByKey())
  41. .forEach(e -> System.out.println(e.getKey() + " → " + e.getValue()));
  42. }
  43.  
  44. public static void main(String[] args) {
  45. String input = "This is a test. This is only a test";
  46. Map<String, Integer> counts = countWords(input);
  47.  
  48. printSortedByKey(counts);
  49. }
  50. }
  51.  
  52.  
  53.  
Success #stdin #stdout 0.17s 56600KB
stdin
Standard input is empty
stdout
a → 2
is → 2
only → 1
test. → 2
this → 2