查询数组中相同元素的个数

查询数组中相同元素的个数


1.定义一个String数组

    String[] txtStrs = ["L","H","C","L","L","L","H","H","C"];

2.创建一个HashMap来存放数组的信息,HashMap的键为元素,值为该元素出现的次数

HashMap map = new HashMap();
        for(String str:txtStrs){
            int i = 1;
            if(map.get(str) != null){
                i = map.get(str) + 1;
            }
            map.put(str, i);
        }

3.遍历HashMap,获取元素的信息和个数,将其拼接成字符串

        Iterator> iter = map.entrySet().iterator();
        String txtAfterFormat = "";
        while (iter.hasNext()) {
            Entry entry = iter.next();
            String key = (String) entry.getKey();
            int val = (Integer) entry.getValue();
            txtAfterFormat = txtAfterFormat + key + "_" + val + ";";
        }

4.结果为: L_4;H_3;C_2;

你可能感兴趣的:(java)