I have a HashMap and now i need to find all the keys inside the HashMap which has a particular letter inside it and replace it with another letter
You could try this :
public void replaceKeysChar(char originalChar, char newChar, Map<String, ?> map) {
Map<String, Object> tempMap = new HashMap<String, Object>();
for (Map.Entry<String, ?> entry : map.entrySet()) {
String key = entry.getKey();
if(key != null){
key = key.replace(originalChar, newChar);
}
tempMap.put(key, entry.getValue());
}
map.clear();
map.putAll(tempMap);
}
This way you handle only char, and you don't change the implementation. Plus when you iterate you don't add item in your map (it would be a bad idea).
If you don't care about the implementation simply return the tempMap and remove the clear/putAll part (it will consume less resources).
EDIT :
After @locka's answer I think I should specify that this method can't handle collisions.
If your Map contains the keys "toto" and "tata" and you do a `replaceKeysChar('a','o', map) only one of the values between "toto"'s value and "tata"'s value will be in the map, the other will simply be ignored.
EDIT bis:
To handle collisions with exceptions (à la @Stephen C) just replace the old for by this one :
for (Map.Entry<String, ?> entry : map.entrySet()) {
String key = entry.getKey();
if(key != null){
key = key.replace(originalChar, newChar);
}
if(tempMap.containsKey(key))
throw new CollisionException();
tempMap.put(key, entry.getValue());
}
Here's a solution that "deals with" collisions by throwing an exception.
public void replaceKeysChar(char originalChar, char newChar, Map<String, ?> map) {
Map<String, Object> tempMap = new HashMap<String, Object>();
Set<String> tempSet = new HashSet<String>();
for (Map.Entry<String, ?> entry : map.entrySet()) {
String originalKey = entry.getKey();
String newKey = originalKey .replace(originalChar, newChar);
if (!newKey.equals(originalKey)) {
if (map.containsKey(newKey) || tempMap.containsKey(newKey)) {
throw new CollisionException(newKey);
}
tempMap.put(newKey, entry.getValue());
tempSet.add(originalKey());
}
}
map.keySet().removeAll(tempSet);
map.putAll(tempMap);
}
EDIT
Fixed bugs ... in previous versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With