Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.Map.*;
- import java.util.stream.*;
- public class MapUtils {
- // Java 8 - Functional
- public static final <T, U> Map<U, List<T>> invertMap(Map<T, U> map) {
- HashMap<U, List<T>> invertedMap = new HashMap<>();
- for (T key : map.keySet()) {
- U newKey = map.get(key);
- invertedMap.computeIfAbsent(newKey, k -> new ArrayList<>());
- invertedMap.get(newKey).add(key);
- }
- return invertedMap;
- }
- // Java 8 - Streams
- public static final <T, U> Map<U, List<T>> invertMap2(Map<T, U> map) {
- return map.entrySet().stream().collect(Collectors.groupingBy(Entry::getValue,
- Collectors.mapping(Entry::getKey, Collectors.toList())));
- }
- // Java 5 - 7
- public static final <T, U> Map<U, List<T>> invertMap3(Map<T, U> map) {
- HashMap<U, List<T>> invertedMap = new HashMap<>();
- for (T key : map.keySet()) {
- U newKey = map.get(key);
- List<T> list = invertedMap.containsKey(newKey) ? invertedMap.get(newKey) : new ArrayList<T>();
- list.add(key);
- invertedMap.put(newKey, list);
- }
- return invertedMap;
- }
- public static void main(String[] args) {
- HashMap<Integer, String> original = new HashMap<Integer, String>() { {
- put(1, "A");
- put(2, "B");
- put(3, "C");
- put(4, "A");
- } };
- Map<String, List<Integer>> inverted = invertMap(original);
- System.out.println(original);
- System.out.println(inverted);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement