java_程序题总结:统计一个数组中每个元素出现的次数

package 程序题;

import java.util.HashMap;
import java.util.Map;

/**
 * 统计一个数组中每个元素出现的次数
 * @author 朱方圆
 *
 */
public class T2 {
    
    
	public static void main(String[] args) {
    
    
		
		String[] str = {
    
    "j","f","o","i","1","3","a","e"};//定义一个字符串数组str
		
		Map<Character, Integer> counter = new HashMap<Character,Integer>();//定义一个map集合
		
		//循环遍历数组中的元素
		for(int i = 1; i < str.length; i++) {
    
    
			
			Character currentChar = str[i].charAt(i);
			
			if(!counter.containsKey(currentChar)) {
    
    
				
				counter.put(currentChar,1);
				
			}else {
    
    
				
				int oldValue = counter.get(currentChar);
				counter.put(currentChar, oldValue + 1);
				
			}	
		}
		
		for(Map.Entry<Character, Integer> entry : counter.entrySet()) {
    
    
			
			System.out.println(entry);
			
		}
	}
}

猜你喜欢

转载自blog.csdn.net/zhu_fangyuan/article/details/108292428