(74)TreeMap练习:求字符串中每个字符出现的次数(键值对:字符---次数)

什么时候使用map集合呢?
当数据之间存在映射关系时,就要先想到map集合

需求:获取字符串中的字母出现的次数
希望打印结果为:a(1) c(2)…..
通过结果发现,每一个字母都有对应的次数,说明字母和次数之间存在映射关系。
思路:
1、将字符串转换为字符数组,因为要对每个字母进行操作。
2、定义一个map集合,因为打印结果字符有顺序,所以使用treemap集合。
3、遍历字符数组
3.1 将每一个字母作为键去查map集合
3.2如果返回为null,说明集合中没有这个元素,应该将字母和1存入到map集合中。
3.3如果返回的不是null,说明该字母在map集合中已经存在,并且有对应的次数,那 么就应该获得这个次数,并进行自增,然后将该字母和 自增后的次数存入到map集合中,覆盖调原来键对应的值。
4、将map集合中的数据变成指定的字符串形式返回

public class StringLength {

    public static TreeMap everCharLen(String str) {
        TreeMap<Character,Integer> map=new TreeMap<Character,Integer>();
        for(int i=0;i<str.length();i++) {
            char temp=str.charAt(i);
            if(!map.containsKey(temp)) {
                map.put(temp, new Integer(1));
            }
            else {
                int count=map.get(new Character(temp));
                count++;
                map.put(new Character(temp), count);
            }
        }
        return map;
    }
    public static void main(String[] args) {
        String str="abcdbcddca";
        TreeMap<Character,Integer> map=new TreeMap<Character,Integer>();
        map=everCharLen(str);

        Set<Character> s=map.keySet();
        Iterator<Character> it=s.iterator();
        while(it.hasNext()) {
            char ch=it.next();
            Character ch1=new Character(ch);
            System.out.println(ch+"("+map.get(ch1)+")");
        }




    }
}
posted @ 2017-07-18 17:59  测试开发分享站  阅读(71)  评论(0编辑  收藏  举报