说我有一个数组
[bob, alice, jeff, bob, bob]
我想将此数组转换为
[bob, alice, jeff, bob1, bob2]
也就是确定发生次数。
// iterate through array
// check if element is in finalArray
// if not add to finalArray
// if found in final array
// add in duplicateArray
// check instances of element in duplicateArray and add that number to element
// insert element+updated number to finalArray
这是我对上述算法的实现
ArrayList<String> list = new ArrayList<>();
list.add("Bob");
list.add("Jane");
list.add("Smith");
list.add("Bob");
list.add("Bob");
list.add("Jane");
list.add("Smithery");
ArrayList<String> finalList = new ArrayList<>();
ArrayList<String> tempList = new ArrayList<>();
for(String name : list) {
if(finalList.contains(name)) {
int count = 0;
tempList.add(name);
for(int i=0; i < tempList.size(); i++) {
if(tempList.get(i) == name) {
count++;
}
}
String tempName = name + count;
finalList.add(tempName);
} else {
finalList.add(name);
}
}
for(String name: finalList) {
System.out.println(name);
}
我的问题是,尽管ArrayList
和其他数据结构具有.contains
方法,但是任何数据结构都具有返回数据结构中元素实例数量的方法吗?
答案 0 :(得分:0)
List<String> data = ...;
List<String> finalData = new ArrayList<>();
Map<String, Integer> counts = new HashMap<>();
for(String s : data) {
counts.merge(s, 1, Integer::sum); // Keep track of occurences seen
int occurences = counts.get(s); // Get how many there are for s
if(occurences == 1) {
finalData.add(s);
}
else { // if more than 1, change the string
finalData.add(s + (occurences - 1));
}
}
现在真正的问题是,如果列表中两次出现“ Bob”,而原始列表中也出现了“ Bob1”,该怎么办...
答案 1 :(得分:0)
这是我目前有效的编码实现。
ArrayList<String> list = new ArrayList<>();
list.add("Bob");
list.add("Jane");
list.add("Smith");
list.add("Bob");
list.add("Bob");
list.add("Jane");
list.add("Smithery");
ArrayList<String> finalList = new ArrayList<>();
ArrayList<String> tempList = new ArrayList<>();
for(String name : list) {
if(finalList.contains(name)) {
int count = 0;
tempList.add(name);
for(int i=0; i < tempList.size(); i++) {
if(tempList.get(i) == name) {
count++;
}
}
String tempName = name + count;
finalList.add(tempName);
} else {
finalList.add(name);
}
}
for(String name: finalList) {
System.out.println(name);
}