Skip to content

Instantly share code, notes, and snippets.

@OkiStuff
Created July 1, 2024 23:50
Show Gist options
  • Save OkiStuff/e3a120a2d98f16ce43d9643161bfdb9a to your computer and use it in GitHub Desktop.
Save OkiStuff/e3a120a2d98f16ce43d9643161bfdb9a to your computer and use it in GitHub Desktop.
updated map transformer
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 static <K, V> Map<K, V> transform(Map<K, V> original, Transformation<K> keyTransformation, Transformation<V> valueTransformation)
{
return new MapTransformer<K, V>(keyTransformation, valueTransformation).transform(original);
}
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