使用 Hashmap 检测列表中的重复项和重复项计数

Using a Hashmap to detect duplicates and count of duplicates in a list

我正在尝试使用哈希映射来检测给定列表中的任何重复项,如果有,我想向该字符串添加“1”以指示其重复项。如果它出现 3 次,则第三次将在该字符串后添加“3”。

我似乎无法弄清楚,跟踪重复项的数量。它只对重复项加 1,无论是第二个、第三个或第四个,..等重复项。

这是我的:

public static List<String> duplicates(List<String> given) {
     List<String> result = new ArrayList<String>();
     HashMap<String, Integer> hashmap = new HashMap<String, Integer>();

     for (int i=0; i<given.size(); i++) {
       String current = given.get(i);
       if (hashmap.containsKey(current)) {
           result.add(current+"1");
       } else {
           hashmap.put(current,i);
           result.add(current);
       }
     }

     return result;
 }

我也想按原样包括只出现一次的值(没有串联)。

示例输入:[“搅拌机”、“烤面包机”、“搅拌机”、“搅拌机”、“碗”]

示例输出:[“搅拌机”、“烤面包机”、“搅拌机 1”、“搅拌机 2”、“碗”]

我将final重命名为output,因为第一个是关键字,不能用作变量名。

if (hashmap.containsKey(current)) {
    output.add(current + hashmap.get(current)); // append the counter to the string
    hashmap.put(current, hashmap.get(current)+1); // increment the counter for this item
} else {
    hashmap.put(current,1); // set a counter of 1 for this item in the hashmap
    output.add(current);
}

您始终添加硬编码字符串“1”而不是使用地图中保存的计数:

public static List<String> duplicates(List<String> given) {
    List<String> result = new ArrayList<>(given.size());
    Map<String, Integer> hashmap = new HashMap<>();

    for (String current : given) {
        if (hashmap.containsKey(current)) {
            int count = hashmap.get(current) + 1;
            result.add(current + count);
            hashmap.put(current, count);
        } else {
            hashmap.put(current, 0);
            result.add(current);
        }
    }

    return result;
}
ArrayList finallist = new ArrayList<String>();
    
    for (int i=0; i<given.size(); i++) {
       String current = given.get(i);
       if (hashmap.containsKey(current)) {
            hashmap.put(current,hashmap.get(current)+1);
       } else {
           hashmap.put(current,1); 
                 
       }
       String num = hashmap.get(current) == 1 ? "" :Integer.toString(hashmap.get(current));
       finallist.add(current+num);
     }
     
     System.out.println(finallist);
public static List<String> duplicates(List<String> given) {
    final Map<String, Integer> count = new HashMap<>();
    return given.stream().map(s -> {
        int n = count.merge(s, 1, Integer::sum) - 1;
        return s + (n < 1 ? "" : n);
    }).collect(toList());
}