时间:2020-11-13 08:59:55 | 栏目:JAVA代码 | 点击:次
java 查找list中重复数据实例详解
需求:
查找一个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(".................."); }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!