日期:2014-05-17  浏览次数:20769 次

string 数组 删除重复并统计
我有一个string数组中文的 如何删除其中的重复项,并统计重复项的数目
比如String[] old ="类目一','类目二','类目三','类目一','类目三'";
如何得到一个新数组string [] new= ="'类目一','类目二','类目三'";
并得到类目一个数 2  
类目二 个数1 类目三个数2

------解决方案--------------------
Java code

String[] old = { "类目一", "类目二", "类目三", "类目一", "类目三" };
        List<String> list = new ArrayList<String>();
        for (String str : old) {
            if (!list.contains(str)) {
                list.add(str);
            }
        }
        String[] dest = new String[list.size()];
        list.toArray(dest);
        for (String str : dest) {
            System.out.println(str);
        }

------解决方案--------------------
1楼可以,另外用map也可以,不用判断。
------解决方案--------------------
自己看着需要修改。。。

Java code

    public static void main(String[] args) throws Exception {

        String[] old = { "类目一", "类目二", "类目三", "类目一", "类目三" };
        Map<String, Integer> map = new TreeMap<String, Integer>();

        for (String key : old) {
            if (map.containsKey(key)) {
                map.put(key, map.get(key) + 1);
            } else {
                map.put(key, 1);
            }
        }

        String[] des = new String[map.size()];

        int i = 0;
        for (String key : map.keySet()) {
            des[i++] = key + " : " + map.get(key);
        }

        System.out.println(Arrays.toString(des));
    }

------解决方案--------------------

Java code
public static String[] replace(String[] array, Map<String, Integer> map) {
        if (array != null && array.length > 0) {
            int len = array.length, v = 0;
            for (int i = 0; i < len; i++) {
                if (map.containsKey(array[i])) {
                    v = map.get(array[i]);
                    map.put(array[i], v + 1);
                } else
                    map.put(array[i], 1);
            }
            //            System.out.println(map.entrySet());
            return map.keySet().toArray(new String[map.keySet().size()]);

        }
        return array;
    }
  public static void main(String[] args) {
        String[] old = new String[] { "类目一", "类目二", "类目三", "类目一", "类目三" };
        Map<String, Integer> map = new HashMap<String, Integer>();
        print(replace(old, map));
        System.out.println(map);
        //        print(old);
    }

------解决方案--------------------
Java code


String[] old = { "类目一", "类目二", "类目三", "类目一", "类目三" };
Map<String,Integer> map = new HashMap<String,Integer>();        
for(int i =0;i<old.length;i++){
  if(!map.containsKey(old[i]))
     map.put(old[i], 1);
  else
    map.put(old[i], map.get(old[i]+1));
}