集合使用举例

1.需求:给定一个字符串中字符的使用次数?如bbbssdffsahdh

用map实现。

import java.util.Map;
import java.util.TreeMap;

public class Maptest {

    public static  Map<Character,Integer> countChar(Map<Character,Integer> map,String str) {
        char[] chars = str.toCharArray();
        for(char c:chars) {
            if(map.containsKey(c)) {
                int oldCount = map.get(c)==null?0:map.get(c);
                map.put(c, oldCount++);
            } else {
                map.put(c, 1);
            }
            
        }
        return map;
    }
    
    public static void main(String []args){
        String str = "hello world";
        // 无序
        //Map<Character,Integer> map =countChar(str);
        // 根据字符串的顺序给出
        //Map<Character,Integer> linkedHashMap = countChar(str);
        // treeMap有序
        Map<Character,Integer> treeMap = new TreeMap<Character, Integer>();
        
        System.out.println(countChar(treeMap,str).toString());
    }
}
 

猜你喜欢

转载自blog.csdn.net/weixin_40018934/article/details/81068720