使用Hashmap来检测重复项并对列表中的重复项进行计数



我试图使用hashmap来检测给定列表中的任何重复项,如果有,我想添加"1"赋给该字符串以表示它的重复。如果出现3次,第三次就加"3";

我似乎不能弄清楚,跟踪重复的数量。它只给重复项加1,不管它是第2、3还是4,…等重复。

这是我的:

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

我想包括只出现一次的值,就像这样(没有串联)。

样本输入:["mixer", "toaster", "mixer", "mixer", "bowl"]

输出示例:["mixer", "toaster", "mixer1", "mixer2", "bowl"]

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

我将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);

相关内容

  • 没有找到相关文章

最新更新