15-wordcount-in-one-line
15. 巧用HashMap一行代码统计单词出现次数
简介
爱在JDK8之前
public void countBefore8(){
Map<String,Integer> wordCount= new HashMap<>();
String[] wordArray= new String[]{"we","are","the","world","we"};
for(String word: wordArray){
//如果存在则加1,否则将值设置为1
if(wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
}else{
wordCount.put(word, 1);
}
}
}JDK8中使用compute
JDK8中使用merge
最后更新于
这有帮助吗?