Map--读"找出数组中重复次数最多的元素并打印"有感Map的使用

目的:了解Map的containsKey的是用以及Map的遍历:


  

 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 从一数组中找出出现最多的字符 引发对Map的总结 1.containsKey(Object key)方法的使用 2.Map的遍历操作
 */
public class MapTest {

	public static void findSameNum(String[] arr) {

		Map<String, Integer> map = new HashMap<String, Integer>();
		for (int i = 0; i < arr.length; i++) {
			/*
			 * map.containsKey(Object findKey) 
			 * 方法介绍: 如果此映射包含指定键的映射关系,则返回 true。
			 * 说明:map已经包含了findKey的映射关系 则返回true 否则返回false
			 */
			if (map.containsKey(arr[i])) {
				int tempCount = map.get(arr[i]);
				map.put(arr[i], ++tempCount);
			} else {
				map.put(arr[i], 1);
			}
		}

		/*
		 * Map的遍历操作 map.entrySet().iterator(); map.getKey() map.getValue()
		 */
		Iterator<Entry<String, Integer>> it = map.entrySet().iterator();
		int count = 0; // 全局记录某数字出现的最多的次数
		String maxCountWord = arr[0]; // 默认出现最多的字符是第一个
		while (it.hasNext()) {
			Entry<String, Integer> en = it.next();
			int tempCount = en.getValue();
			if (tempCount > count) {
				count = tempCount;
				maxCountWord = en.getKey();
			}
		}
		System.out.println("最终胜出:" + maxCountWord + "出现" + count + "次!");

	}


	public static void main(String[] args) {
		String[] arr = { "hello", "world", "a", "k", "a", "bf", "aa", "z", "a",
				"1", "c" };
		MapTest.findSameNum(arr);
	}

}

 

参考:http://www.iteye.com/topic/777508

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值