Word Count

Lab Java Beginner 10 points

Read a line of words and count each word with a HashMap<String, Integer>. Print the words in alphabetical order with their counts (copy into a TreeMap to sort).

Input

One line.

Output

One line per word: word count

Example

Input

to be or not to be

Output

be 2
not 1
or 1
to 2
Sample input available Sample output available
Editor
Java

Hints

get() returns null for a missing key.

A TreeMap keeps its keys sorted.

Solution explanation

A HashMap has no predictable order; never rely on its iteration order in output.

Show solution
import java.util.HashMap;
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);
        Map<String, Integer> counts = new HashMap<String, Integer>();
        for (String w : sc.nextLine().trim().split("\\s+")) {
            Integer old = counts.get(w);
            counts.put(w, old == null ? 1 : old + 1);
        }
        for (Map.Entry<String, Integer> e : new TreeMap<String, Integer>(counts).entrySet()) {
            System.out.println(e.getKey() + " " + e.getValue());
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD