從一個英文字串中找出每個單詞出現的頻率
阿新 • • 發佈:2019-02-18
import java.util.*; public class Lookup{ public static void main(String[] args){ String s = "the instruction set of the Java virtual machine distinguishes its operand types using instructions intended to operate on values of specific types"; String[] word = s.split(" "); Map<String,Integer> m = new HashMap<String,Integer>(); //用word初使化m,m中包含了所有不重複的單詞 for(int j=0;j<word.length;j++){ m.put(word[j],0); } Set<String> set = m.keySet(); //用word中的每個單詞與m中的單詞比較,發現相同的就統計一次 for(int i=0;i<word.length;i++){ Iterator<String> it = set.iterator(); while(it.hasNext()){ String k = it.next(); if(word[i].equals(k)){ int c = m.get(k); c++; m.put(word[i],c); } } } System.out.println(m); } }