Reputation: 15
I have a hashmap which contains student id as key and some string as value. It contains data like
a abc.txt
b cde.txt
d abc.txt
I want to find the duplicate values in map and replace them with genreic values. I want a map like
a abc.txt
b cde.txt
d abc_replacevalue.txt
I have tried with the code but its not working
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);
}
The output is still the same
a abc.txt
b cde.txt
d abc.txt
Upvotes: 0
Views: 189
Reputation: 4532
You can generate a new map from an existing one, checking every new value that you come across to see if it has already been seen:
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);
}
Upvotes: 2