Program counts the number of occurrences of each word in a String. - Java Collection Framework

Java examples for Collection Framework:Set

Description

Program counts the number of occurrences of each word in a String.

Demo Code

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Map<String, Integer> myMap = new HashMap<>();

    createMap(myMap); // create map based on user input
    displayMap(myMap); // display map content
  }/*from   ww  w  .j a va  2s .  c o  m*/

  private static void createMap(Map<String, Integer> map) {
    String input = "this is a test this is a test";

    String[] tokens = input.split(" ");

    // processing input text
    for (String token : tokens) {
      String word = token.toLowerCase(); // get lowercase word

      // if the map contains the word
      if (map.containsKey(word)) // is word in map
      {
        int count = map.get(word); // get current count
        map.put(word, count + 1); // increment count
      } else
        map.put(word, 1); // add new word with a count of 1 to map
    }
  }

  // display map content
  private static void displayMap(Map<String, Integer> map) {
    Set<String> keys = map.keySet(); // get keys

    // sort keys
    TreeSet<String> sortedKeys = new TreeSet<>(keys);

    System.out.printf("%nMap contains:%nKey\t\tValue%n");

    // generate output for each key in map
    for (String key : sortedKeys)
      System.out.printf("%-10s%10s%n", key, map.get(key));

    System.out.printf("%nsize: %d%nisEmpty: %b%n", map.size(), map.isEmpty());
  }
}

Result


Related Tutorials