Advertisement
MrPolywhirl

MapUtils.java

Dec 6th, 2016
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.Map.*;
  3. import java.util.stream.*;
  4.  
  5. public class MapUtils {
  6.     // Java 8 - Functional
  7.     public static final <T, U> Map<U, List<T>> invertMap(Map<T, U> map) {
  8.         HashMap<U, List<T>> invertedMap = new HashMap<>();
  9.  
  10.         for (T key : map.keySet()) {
  11.             U newKey = map.get(key);
  12.  
  13.             invertedMap.computeIfAbsent(newKey, k -> new ArrayList<>());
  14.             invertedMap.get(newKey).add(key);
  15.  
  16.         }
  17.  
  18.         return invertedMap;
  19.     }
  20.  
  21.     // Java 8 - Streams
  22.     public static final <T, U> Map<U, List<T>> invertMap2(Map<T, U> map) {
  23.         return map.entrySet().stream().collect(Collectors.groupingBy(Entry::getValue,
  24.                 Collectors.mapping(Entry::getKey, Collectors.toList())));
  25.     }
  26.  
  27.     // Java 5 - 7
  28.     public static final <T, U> Map<U, List<T>> invertMap3(Map<T, U> map) {
  29.         HashMap<U, List<T>> invertedMap = new HashMap<>();
  30.  
  31.         for (T key : map.keySet()) {
  32.             U newKey = map.get(key);
  33.             List<T> list = invertedMap.containsKey(newKey) ? invertedMap.get(newKey) : new ArrayList<T>();
  34.  
  35.             list.add(key);
  36.             invertedMap.put(newKey, list);
  37.  
  38.         }
  39.  
  40.         return invertedMap;
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         HashMap<Integer, String> original = new HashMap<Integer, String>() { {
  45.             put(1, "A");
  46.             put(2, "B");
  47.             put(3, "C");
  48.             put(4, "A");
  49.         } };
  50.  
  51.         Map<String, List<Integer>> inverted = invertMap(original);
  52.  
  53.         System.out.println(original);
  54.         System.out.println(inverted);
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement