Created
June 23, 2024 17:51
-
-
Save OkiStuff/200bc6e65fe18f557c58a2aa62c8093a to your computer and use it in GitHub Desktop.
Helper class to transform values in map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Set; | |
public class MapTransformer<K, V> | |
{ | |
private Transformation<K> keyTransformation; | |
private Transformation<V> valueTransformer; | |
public MapTransformer(Transformation<K> keyTransformation, Transformation<V> valueTransformer) | |
{ | |
this.keyTransformation = keyTransformation; | |
this.valueTransformer = valueTransformer; | |
} | |
// Assumes transformed is empty | |
public void transform(Map<K, V> original, Map<K, V> transformed) | |
{ | |
Set<Map.Entry<K, V>> entrySet = original.entrySet(); | |
for (Map.Entry<K, V> entry : entrySet) | |
{ | |
transformed.put(keyTransformation.callback(entry.getKey()), valueTransformer.callback(entry.getValue())); | |
} | |
} | |
public Map<K,V> transform(Map<K, V> original) | |
{ | |
Map<K, V> transformedMap = new HashMap<K, V>(); | |
this.transform(original, transformedMap); | |
return transformedMap; | |
} | |
public void transformInPlace(Map<K, V> map) | |
{ | |
Set<Map.Entry<K, V>> entrySet = map.entrySet(); | |
map.clear(); | |
for (Map.Entry<K, V> entry : entrySet) | |
{ | |
map.put(keyTransformation.callback(entry.getKey()), valueTransformer.callback(entry.getValue())); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Transformation<T> | |
{ | |
public T callback(T val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment