查找list中重复数据

2019-01-08  本文已影响3人  奇点一氪

需求:
查找一个List集合中所有重复的数据,重复的数据可能不止一堆,比如:aa, bb, aa, bb, cc , dd, aa这样的数据。如果有重复数据,则给这些重复数据加上编号,上述数据改为:aa1, bb1, aa2, bb2, cc, dd.

public static void same(List<String> list) {
        String [] indexArr ;
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i);
            String old = map.get(key);
            if (old != null) {
                map.put(key, old + "," + (i + 1));
            } else {
                map.put(key, "" + (i + 1));
            }
        }
        Iterator<String> it = map.keySet().iterator();
        int index = -1;
        while (it.hasNext()) {
            String key = it.next();
            String value = map.get(key);
            if (value.indexOf(",") != -1) {
                System.out.println(key + " 重复,行: " + value);
                indexArr = value.split(",");

                for (int i = 0; i < indexArr.length; i++) {
                    index = Integer.parseInt(indexArr[i])-1;
                    list.set(index, list.get(index)+(1+i));
                }
            }
        }

        for (String val : list) {
            System.out.println("val = "+val);
        }
        System.out.println("..................");

    }
上一篇下一篇

猜你喜欢

热点阅读