java - 用于计数出现次数的数据结构

标签 java duplicates multiset bag

假设我有一个数组

[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/

相关文章:

java - Kotlin lambda 主体中的 `it` 是什么?

bash - 删除分隔符之间的重复文本

streaming - 数据流中的近似重复检测

java - 从子类设置父类(super class)中字段的类型 (Java)

java - JBoss AS 7.1 JBREM000200 : Remote connection failed: java. io.IOException:已建立的连接被主机中的软件中止

java - 如何在Java中打印没有分号的Hello World?

php - MySQL插入防止双重

prolog - 在 prolog 中为多重集编写并集运算

scala - Scala中缺少多集吗?

c++ - 二进制搜索以在 STL C++ 多重集中查找小于或等于的值