java统计字符串数组中每个字符串所出现的次数
统计字符串数组中每个字符串所出现的次数
public class StringSameCount { private HashMap map; private int counter; public StringSameCount() { map = new HashMap<String,Integer>(); } public void hashInsert(String string) { if (map.containsKey(string)) { //判断指定的Key是否存在 counter = (Integer)map.get(string); //根据key取得value map.put(string, ++counter); } else { map.put(string, 1); } } public HashMap getHashMap(){ return map; } }
测试调用如下:
public class Main { public static void main(String[] args) { StringSameCount ssc = new StringSameCount(); ssc.hashInsert("ab"); ssc.hashInsert("ac"); ssc.hashInsert("acd"); ssc.hashInsert("acd"); ssc.hashInsert("asc"); ssc.hashInsert("afc"); ssc.hashInsert("avc"); ssc.hashInsert("ac"); HashMap map = ssc.getHashMap(); Iterator it = map.keySet().iterator(); String temp; while (it.hasNext()) { temp = (String)it.next(); System.out.println(temp+"出现了"+map.get(temp)+"次"); } System.out.println(map); } }
运行结果如下:
avc出现了1次
afc出现了1次
asc出现了1次
ac出现了2次
ab出现了1次
acd出现了2次
{avc=1, afc=1, asc=1, ac=2, ab=1, acd=2}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: Kylin - 剪枝优化及其方法
- 下一篇: yii2.0的session