本帖最后由 zzdhm 于 2016-9-17 00:06 编辑  
 
public static int frequency(List<String> list, String string) { 
                HashMap<String, Integer> hm = new HashMap<>(); // 创建HashMap集合,键为要list集合中的元素,值为出现的个数 
               for (String st : list) {             // 遍历,将元素到hm集合中 
                        if (hm.containsKey(st)) {        // 判断是否集合中包含 
                                hm.put(st, hm.get(st) + 1);      // 包含值加1 
                        } else { 
                                hm.put(st, 1);                 // 不包含 值为1 
                        } 
 
                } 
                if (!hm.containsKey(string)) {           // 循环完,没有该字符串,返回0 
                        return 0; 
                } 
 
                return hm.get(string);                // 返回键对应的值 
        } 
//方法2 : 
public static int frequency(List<String> list, String string) { 
                int count=0; 
                for (String st : list) { 
                        if(string.equals(st)){ 
                                count++; 
                        } 
                } 
                return count; 
        } 
 
 
 
 
 |