Skip to content

Instantly share code, notes, and snippets.

@dmlloyd
Created October 1, 2022 15:13
Show Gist options
  • Save dmlloyd/51eca0d6807a9a7156dbf20e9e74da84 to your computer and use it in GitHub Desktop.
Save dmlloyd/51eca0d6807a9a7156dbf20e9e74da84 to your computer and use it in GitHub Desktop.
No good way to transform an immutable map
private static <K1, K2, V1, V2> Map<K2, V2> transform(Map<K1, V1> map, Function<K1, K2> keyTransform, Function<V1, V2> valueTransform) {
Iterator<Map.Entry<K1, V1>> iterator = map.entrySet().iterator();
if (! iterator.hasNext()) {
return Map.of();
}
Map.Entry<K1, V1> entry = iterator.next();
K2 k1 = keyTransform.apply(entry.getKey());
V2 v1 = valueTransform.apply(entry.getValue());
if (! iterator.hasNext()) {
return Map.of(k1, v1);
}
entry = iterator.next();
K2 k2 = keyTransform.apply(entry.getKey());
V2 v2 = valueTransform.apply(entry.getValue());
if (! iterator.hasNext()) {
return Map.of(k1, v1, k2, v2);
}
// ...etc...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment