import java.util.*;

public class CountOccurrenceOfWords {
  public static void main(String[] args) {
    String text = "Have a good day. Have a good class. " +
      "Have a good visit. Have fun!";

    // Create a hash map to hold words as key and count as value
    Map<String, Integer> hashMap = new HashMap<String, Integer>();

    Scanner tokens = new Scanner(text);
    while (tokens.hasNext()) {
        String word = tokens.next();
        if (hashMap.get(word) != null) {
          int value = hashMap.get(word);
          value++;
          hashMap.put(word, value);
        }
        else
          hashMap.put(word, 1);
    }
    
    // Create a tree map from the hash map
    Map<String, Integer> treeMap =
      new TreeMap<String, Integer>(hashMap);

    // Display mappings
    System.out.println("Word counts (sorted by key, the words):");
    System.out.println(treeMap);
  }
}

