Java Data Type How to - Count word frequency








Question

We would like to know how to count word frequency.

Answer

import java.util.ArrayList;
import java.util.Collections;
/*w w  w .jav  a2s. c om*/
public class Main {

  public static void main(String[] args) {
    String givenstring = "this is a test this is a another test";
    String[] words = givenstring.split(" ");

    ArrayList<String> arr = new ArrayList<String>();
    for (int i = 0; i < words.length; i++){
      arr.add(words[i]);
    }
    while (arr.size() != 0) {
      String word = arr.get(0);
      int frequency = Collections.frequency(arr, word);
      arr.removeAll(Collections.singleton(word));
      System.out.println(word + frequency);
    }
  }
}