import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class WordsFreq {
private Map<String,Integer> wordsMap;
public WordsFreq (String strWords){
wordsMap=this.getArray(strWords);
}
//拆分字符串,放入数组,统计数组中相同单词的个数,并放入键值对数组中
private Map<String, Integer> getArray(String strWords) {
// TODO Auto-generated method stub
String[] words_Array=strWords.split("");
Map<String,Integer>words_Map=new HashMap<String,Integer>();
int arrLength=words_Array.length;
for (int i=0;i<arrLength;i++){
if(!words_Map.containsKey(words_Array[i])){
words_Map.put(words_Array[i],1);
}
else{
int currentNum=words_Map.get(words_Array[i])+1;
words_Map.remove(words_Array[i]);
words_Map.put(words_Array[i], currentNum);
}
}
return words_Map;
}
//输出结果
public void OutputResult(){
Set s=wordsMap.keySet();
Iterator i=s.iterator();
while(i.hasNext()){
Object o=i.next();
System.out.println(o+"出现了"+wordsMap.get(o)+"次");
}
}
}
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class WordsFreqTest {
@Test
public void test() {
WordsFreq word=new WordsFreq("Hello World My First Unit Test");
word.OutputResult();
}}