Java Map count word frequency

Description

Java Map count word frequency

import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String args[]) {

    String s = "this is a test from demo2s.com this is a test from demo2s.com";
    String[] splitted = s.split(" ");
    Map<String, Integer> counterMap = new HashMap<String, Integer>();

    for (int i = 0; i < splitted.length; i++) {
      if (counterMap.containsKey(splitted[i])) {
        int cont = counterMap.get(splitted[i]);
        counterMap.put(splitted[i], cont + 1);
      } else {//  w ww.ja v  a  2s  .co  m
        counterMap.put(splitted[i], 1);
      }
    }
    System.out.println(counterMap);
  }
}



PreviousNext

Related