java HashMap其中一个特点就是在同一个hashmap对象中不允许存在相同的主键,即“key"值,但'value”域是没有这个限制的。在实际使用时,如果后面再次向hashmap中插入的数据的主键在前面已经存在,那么后面的数据就直接将前面的数据覆盖掉,比如我在使用
hashmap.put("first", 1);
hashmap.put("second", 2);
后,我再次执行hashmap.put("first', 3),因为first主键已经存在,所以实际上hashmap中还是只有first和second两个主键,但是first的值已经被覆盖为3。
我们可以使用这个特性来统计输入的每个单词的个数和不同的单词一共有多少个,只需要在每次插入新的数据是检查当前的主键是否已经存,如果已经存在,就获取这个主键对应的值(这里主键就是输入的单词,键值就是这个单词出现的次数)然后加1后再插入就能实现统计,最后使用hashmap.size()输出的就是不同的单词一共有多少个,遍历hashmap就能得到输入的单词和每个单词出现的次数。以下是java的代码实现:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
public class TEST {
public static void main(String[] args) {
HashMap<String, Integer> words = new HashMap<>();
Scanner in = new Scanner(System.in);
String word;
while (!((word = in.nextLine()).equals(""))) {//如果输入为空的时候终止输入
int count = 1;//默认一个单词就是出现一次
if (words.containsKey(word)) {//判断刚输入的单词是否已经存在
count = words.get(word) + 1;//如果已经存在,新的个数就在已有的个数上加1
}
words.put(word, count);//插入新的数据
}
in.close();
System.out.println("total have " + words.size() + " unique words");
//遍历hashmap,遍历方式较list要麻烦一点,谁叫他功能更丰富
Iterator<Entry<String, Integer>> iterator = words.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Integer> entry = (Entry<String, Integer>) iterator.next();
System.out.println("you input \"" + entry.getKey() + "\" " + entry.getValue() + " times");
}
}
}
测试样例:
hello
world
hello
c++
hello
java
total have 4 unique words
you input "c++" 1 times
you input "world" 1 times
you input "java" 1 times
you input "hello" 3 times