Skip to content

Instantly share code, notes, and snippets.

@dstoianov
Last active October 8, 2021 20:01
Show Gist options
  • Save dstoianov/79c61618ee368a3fa5de0cbadabfe7a7 to your computer and use it in GitHub Desktop.
Save dstoianov/79c61618ee368a3fa5de0cbadabfe7a7 to your computer and use it in GitHub Desktop.
MultiValueMap and Transformer
import java.util.*;
public class MultiValueMapConverter {
public static void main(String[] args) {
/*
0 -> [0]
1 -> [0]
2 -> [1]
3 -> [3]
4 -> [5,6,7]
5 -> [2]
*/
MultiValueMap<Integer, Integer> engToEspMap = new MultiValueMap<>();
engToEspMap.put(0, 0);
engToEspMap.put(1, 0);
engToEspMap.put(2, 1);
engToEspMap.put(3, 3);
engToEspMap.put(4, List.of(5, 6, 7));
engToEspMap.put(5, 2);
/* should be
0 -> [0,1]
1 -> [2]
2 -> [5]
3 -> [3]
4 -> [] // not handled case, not implemented
5 -> [4]
6 -> [4]
7 -> [4]
*/
MultiValueMap<Integer, Integer> espToEngMap = transform(engToEspMap);
System.out.println(espToEngMap);
}
private static MultiValueMap<Integer, Integer> transform(MultiValueMap<Integer, Integer> mapToTransform) {
MultiValueMap<Integer, Integer> newMap = new MultiValueMap<>();
for (Integer key : mapToTransform.keySet()) {
for (Integer value : mapToTransform.get(key)) {
newMap.put(value, key);
}
}
return newMap;
}
public static class MultiValueMap<K, V> {
private final Map<K, List<V>> mappings = new HashMap<>();
public List<V> get(K key) {
return mappings.get(key);
}
public Boolean put(K key, List<V> value) {
List<V> target = mappings.get(key);
if (target == null) {
target = new ArrayList<>();
mappings.put(key, target);
}
return target.addAll(value);
}
public Boolean put(K key, V value) {
List<V> target = mappings.get(key);
if (target == null) {
target = new ArrayList<>();
mappings.put(key, target);
}
return target.add(value);
}
public Set<K> keySet() {
return mappings.keySet();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment