- import java.util.Set;
- import java.util.TreeMap;
- /*
- * "aababcabcdabcde",
- * 获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
- *
- * 1.字母 + 出现的次数:可以使用双列集合:Map
- * 2.因为字母不重复,所以使用字母做键;
- * 3.因为需要字母排序,所以使用:TreeMap
- */
- public class Demo {
- public static void main(String[] args) {
- TreeMap<Character,Integer> map = new TreeMap<>();
- String str = "aababcafebcdabcefdefg";
- for(int i = 0;i < str.length() ; i++){
- char c = str.charAt(i);
- //先用c 做键,到集合中查找相应的值
- Integer value = map.get(c);
- //取出的value有两种情况:1.null 2.值
- if(value == null){
- map.put(c, 1);
- }else{
- map.put(c, ++value);
- }
- }
- StringBuffer buf = new StringBuffer();
- Set<Character> keySet = map.keySet();
- for(Character c : keySet){
- buf.append(c).append("(").append(map.get(c)).append(")");
- }
- System.out.println(buf);
- }
- }
复制代码 |
|