Skip to content

Instantly share code, notes, and snippets.

@OkiStuff
Created June 23, 2024 17:51
Show Gist options
  • Save OkiStuff/200bc6e65fe18f557c58a2aa62c8093a to your computer and use it in GitHub Desktop.
Save OkiStuff/200bc6e65fe18f557c58a2aa62c8093a to your computer and use it in GitHub Desktop.
Helper class to transform values in map
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()));
}
}
}
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