Challenge: Word Counter
Completed
Read one line of text. Count how often each word appears (ignore capital letters: The and the are the same word). Print each word and its count in alphabetical order.
Input
One line of words separated by single spaces.
Output
One line per word: <word> <count>.
Example
Input
the cat and The dog
Output
and 1 cat 1 dog 1 the 2
Editor
Java
Hints
toLowerCase() first, then split(" ").
A TreeMap keeps its keys in alphabetical order.
counts.getOrDefault(w, 0) + 1 handles words seen for the first time.
Solution explanation
The map's key is the word and its value is the count. TreeMap sorts the keys for us.
Show solution
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] words = sc.nextLine().trim().toLowerCase().split(" ");
TreeMap<String, Integer> counts = new TreeMap<>();
for (String w : words) {
counts.put(w, counts.getOrDefault(w, 0) + 1);
}
for (Map.Entry<String, Integer> e : counts.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module