Created
October 1, 2022 15:13
-
-
Save dmlloyd/51eca0d6807a9a7156dbf20e9e74da84 to your computer and use it in GitHub Desktop.
No good way to transform an immutable 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
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