黑马程序员技术交流社区
标题:
Map集合练习笔记
[打印本页]
作者:
pengbin
时间:
2015-7-21 09:54
标题:
Map集合练习笔记
/*
* 练习:
* "sdajld;jfijadfaldfoajddf"获取该字符串中的字母出现的次数。
*
* 希望打印结果为:a(1)c(2).......
*
* 通过结果发现,每一个字母都有对应的次数
* 说明字母和次数之间都有映射关系。
*
* 注意了,当发现映射关系时,可以选择map集合
* 因为map集合中存放的就是映射关系。
*
* 什么时候使用map集合呢?
* 当数据之间存在着映射关系时,就要想到map集合。
*
* 思路:
* 1.将字符串转换成字符数组,因为要对每一个字母进行操作
* 2.定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合
* 3.遍历字符数组。
* 将每一个字母作为键去查询map集合。
* 如果返回null,将该字母和1存入到map集合中。
* 如果返回不是null,说明该字母在map集合中已经存在,并有对于的次数
* 那么久获取该次数并进行自增再存入
* 4.将map集合中的数据变成指定字符串形式返回
*/
import java.util.*;
class MapDemo3
{
public static void main(String[] args)
{
String s = charcount("dagdgafdafdg");
System.out.println(s);
}
public static String charcount(String str)
{
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
for(int x=0;x<chs.length;x++)
{
Integer value = tm.get(chs[x]);
if(value==null)
{
tm.put(chs[x], 1);
}
else
{
value = value+1;
tm.put(chs[x], value);
}
}
System.out.println(tm);
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character, Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character, Integer>> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Character, Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+"("+value+")");
}
return sb.toString();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2