0

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
0

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You need to add the updated value anyway so that doesn't actually save anything.
The add that I call can add the updated value, while your one only adds the original value. If you need to update the value within the if block and then add it then you have two calls to add, one of which is also a membership test. Instead I have one membership test and one add.
-.- .... you're absolutely right. I missed, that this call adds the updated value. Nevermind, everything is alright :D.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.