利用HashMap中key不能重复的特性。
案例一:
统计字符串中单词出现的次数。
import java.util.HashMap;
import java.util.Map;
/**
* 统计字符串中单词出现的次数
* @author ly1
*
*/
public class CountNumberOfWords {
/**
* 用HashMap进行分拣存储(1:N)
* @param str
*/
public static void run(String str){
Map<String,Integer> map = new HashMap<>();
String[] words = str.split(" ");
//利用HashMap中key不能重复的特性进行分拣存储
for(int i = 0; i < words.length; i++){
if(map.containsKey(words[i])){
map.put(words[i], map.get(words[i])+1);
}else{
map.put(words[i], 1);
}
}
//将各个单词出现的次数打印出来
for(String key : map.keySet()){
System.out.println(key + "---------->" + map.get(key));
}
}
public static void main(String[] args) {
String str ="When summer comes, the air is stuffy and the"
+"temperature is so high. Thanks to the invention of " +
"air-condition, people are no longer suffer to the hot"+
" weather, they can stay at the indoors and enjoy the"+
" coolness that air-condition brings. But the problem"+
" comes, when people count on air-condition for a long"+
" time, their bodies will be weaker. Some people feel"+
" dizzy and have no strength to do their work, some"+
" people are easy to catch the cold. All of these"+
" symptoms are typical illness which is from air condition."+
" Though air-condition brings us comfort, we will get "+
"sick if we use it all the time. We need to go outside often,"+
" even is hot, what’s more, taking exercise is needed."+
" The natural environment is suitable for us to live in,"+
" we can’t count on air-condition for a long time.";
CountNumberOfWords.run(str);
}
}
案例二(面向对象+分拣存储):
定义一个Student类,属性:姓名:name;班级号:num;分数:score,现在将若干对象放入List中,统计每个班级的总分和平均分。