统计出现次数的数据结构

Data structure for counting occurrences

假设我有一个数组

[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 方法,但是否有任何数据结构具有 return 数据结构中元素实例数的方法?

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" 也在原始列表中时会发生什么...

这是我当前有效的编码实现。

     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);
    }