实现原理:
用HashMap存储该单词以及单词出现的次数。遍历每一个单词,如果单词在HashMap中的键存在,则将该键值对对应的值+1;
如果单词在HashMap中的键不存在,则将该键存储到HashMap中,对应的值为1。
代码实现:
package HashMap; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class HashMapDemo { @SuppressWarnings("preview") public static void main(String[] args){ Map<String,Integer> wordCountStore = new HashMap<>(); String wordString = """ Give me the strength lightly to bear my jobs and sorrows" Give me the strength to make my love fruitful in service Give me the strength never to disown the poor or bend my kneed before insolent migh Give me the strength to raise my mind high above daily trifles """; String[] words = wordString.replace("\n"," ").strip().split(" ");
for (String w:words){
System.out.print(w + " ");
}
for(String word:words){ String key = word.toLowerCase(); Integer value = wordCountStore.get(key); if(value == null){ value = 0; } value++; wordCountStore.put(key,value); } for(Map.Entry<String,Integer> entry: wordCountStore.entrySet()){ String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + ":" + value); } } }
注:上述wordString这个文本段落需要JDK13版本以上才能支持,本实例所选版本为jdk17,首先将该文本转化为文本数组words,遍历words,每个单词转为小写后作为Map的key,如果
Map中该key对应的value,则值累加1,否则先将value置为0,在累加1,最后value的结果存储到Map中。
运行结果如下:
标签:Map,HashMap,value,---,词频,key,words,String From: https://www.cnblogs.com/99kol/p/16965018.html