需求:
查找一个List集合中所有重复的数据,重复的数据可能不止一堆,比如:aa, bb, aa, bb, cc , dd, aa这样的数据。如果有重复数据,则给这些重复数据加上编号,上述数据改为:aa1, bb1, aa2, bb2, cc, dd.
算法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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( ".................." );
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!