zoukankan      html  css  js  c++  java
  • HashMap练习题

    /*
    练习:”asdkljflasdjfl“获取字符出现的个数
    希望打印结果:a(1)c(2)
    通过分析发现,每个字母对应次数,是一种映射关系,
    注意当发现有映射关系的时候,就可以选择map集合。map集合专门用来存储映射关系。
    
    */
    import java.util.*;
    class  TestMap
    {
    	public static void main(String[] args) 
    	{
    		String s = "ababcd";
    		char [] ch =s.toCharArray();
    		HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
    		
    		int count=0;
    		for(int i=0;i<ch.length;i++)
    		{
    			Integer value = hm.get(ch[i]);
    			if(value != null)
    			{
    				count = value;
    			}
    			count++;
    			hm.put(ch[i],count);
    			count = 0;
    			// 方法2
    			/*if(value==null)
    			{
    				hm.put(ch[i],1);
    			}
    			else
    			{
    				value++;
    				hm.put(ch[i],value);
    			}*/
    		}
    
    		System.out.println(hm);
    
    		StringBuilder sb =new StringBuilder();
    		Set<Map.Entry<Character,Integer>> pSet = hm.entrySet();
    		Iterator<Map.Entry<Character,Integer>> pit = pSet.iterator();
    		while(pit.hasNext())
    		{
    			Map.Entry<Character,Integer> pEntry = pit.next();
    			Character key = pEntry.getKey();
    			Integer value = pEntry.getValue();
    			sb.append(key + "(" + value +")");
    		}
    
    		System.out.println(sb);
    	}
    }
    

  • 相关阅读:
    code#5 P2 棋子
    code#5 P1 报告
    ztz11的noip模拟赛T3:评分系统
    20181101noip模拟赛T1
    20181031noip模拟赛T2
    20181031noip模拟赛T1
    Linux进程的五个段
    进程和线程有什么区别
    shell中if条件字符串、数字比对,[[ ]]和[ ]区别
    Python实现单例模式
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258490.html
Copyright © 2011-2022 走看看