`

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

    博客分类:
  • java
阅读更多

目的:了解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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics