Java Data Type How to - Count number of 'x' letter words








Question

We would like to know how to count number of 'x' letter words.

Answer

import java.util.HashMap;
import java.util.Map;
/*  www .j a v  a 2s.com*/
public class Main {
 
  public static void main(String[] args) throws Exception {
    String bubba = "this is a test this is a test";
    Map<Integer,Integer> occurrences = new HashMap<Integer,Integer>(); 

    for(String currentWord: bubba.split(" ")){
        Integer current = occurrences.get(currentWord.length());
        if(current==null){
            current = 0;
        }
        occurrences.put(currentWord.length(), current+1);
    }
    for(Integer currentKey: occurrences.keySet()){
        System.out.println("There are "+occurrences.get(currentKey)+" "+currentKey+" letter words");
    }
  }
}