使用java的hashmap统计输入的单词个数

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



  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值