替换哈希图中的重复值字符串 java
replace duplicate values string in hashmap java
我有一个 hashmap,其中包含学生 ID 作为键和一些字符串作为值。
它包含类似
的数据
a abc.txt
b cde.txt
d abc.txt
我想在地图中找到重复值并将它们替换为通用值。我想要一张像
这样的地图
a abc.txt
b cde.txt
d abc_replacevalue.txt
我已尝试使用代码,但它不起作用
Map<String,String> filemap = new HashMap<String,String>();
// filemap is the original hash map..
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : filemap.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = "updated"; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}
for (String key : result.keySet() ) {
String value = result.get( key );
System.out.println(key + " = " + value);
}
输出还是一样
a abc.txt
b cde.txt
d abc.txt
您可以从现有地图生成新地图,检查您遇到的每个新值以查看它是否已被看到:
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : original.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = ...; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}
我有一个 hashmap,其中包含学生 ID 作为键和一些字符串作为值。 它包含类似
的数据a abc.txt
b cde.txt
d abc.txt
我想在地图中找到重复值并将它们替换为通用值。我想要一张像
这样的地图a abc.txt
b cde.txt
d abc_replacevalue.txt
我已尝试使用代码,但它不起作用
Map<String,String> filemap = new HashMap<String,String>();
// filemap is the original hash map..
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : filemap.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = "updated"; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}
for (String key : result.keySet() ) {
String value = result.get( key );
System.out.println(key + " = " + value);
}
输出还是一样
a abc.txt
b cde.txt
d abc.txt
您可以从现有地图生成新地图,检查您遇到的每个新值以查看它是否已被看到:
Set<String> seenValues = new HashSet<String>();
Map<String, String> result = new HashMap<String, String>();
for (Map.Entry<String, String> entry : original.entrySet()) {
String value = entry.getValue();
if (seenValues.contains(value)) {
value = ...; // update value here
}
result.put(entry.getKey(), value);
seenValues.add(value);
}