Skip to content
UniCircle
EasyCodingCollections: Map

Count words and print them in sorted order (TreeMap)

Question JAVA-COD-103

Count how many times each word appears in a paragraph. A word is a maximal run of letters; compare words case-insensitively and report them in lower case. Print each distinct word and its count in alphabetical order, one per line as word count.

Use a TreeMap in Java and explain why it fits better than a HashMap here.

Constraints

  • 1 ≤ total length ≤ 100000
  • the text contains at least one letter

Input and output

Input
One or more lines of text.
Output
One line per distinct word: the word, a space and its count, in alphabetical order.

Examples

Input 1

The cat and the hat.
The END

Output

and 1
cat 1
end 1
hat 1
the 3

"the" appears three times in different cases; the other words once each.

Input 2

Java, java; JAVA!

Output

java 3

All three are the same word: java 3.

Show hints
  • Split on anything that is not a letter.
  • TreeMap keeps keys sorted, so no separate sort step is needed.
Show the explanation

Split the text with the regular expression [^A-Za-z]+, lower-case each piece and call map.merge(word, 1, Integer::sum). A TreeMap is a red-black tree, so its keys come out in sorted order and each update is O(log d). A HashMap gives O(1) updates but iterates in no particular order, so you would need to sort the keys afterwards. Either is a fine answer if you can explain the trade-off.

Original UniCircle question. Last reviewed 22 Oct 2026.