How to create Map<T, List<K>> out of Map<K, List<T> >?

  • A+

I am trying to implement the function:

private static <T, K> Map<T, List<K> > invertedMap(Map<K, List<T> > m) 

For example if I have Map<String, List<Integer> > ,

I want to create another Map<Integer, List<String> >.

I have written some code:

private static <T, K> Map<T, List<K>> invertedMap(Map<K, T> m) {     return m.keySet().stream()             .collect(Collectors.groupingBy(k -> m.get(k))); } 

but as you can see this only works if the map in the argument doesn't contain list as values.


Here is a stream way of doing it (though my first instinct itself would be to follow Federico's solution) :

private static <T, K> Map<T, List<K>> invertedMapOfList(Map<K, List<T>> m) {     return m.entrySet()         .stream()         .flatMap(e -> e.getValue()             .stream()             .map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v)))         .collect(Collectors.groupingBy(Map.Entry::getValue,             Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: