假设我有一个数组
[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
方法,但是否有任何数据结构具有返回数据结构中元素实例数量的方法?
最佳答案
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”也在原始列表中时会发生什么...
关于java - 用于计数出现次数的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310860/