Java Map Reverse reverseMapping(Map map)

Here you can find the source of reverseMapping(Map map)

Description

reverse a Map to give a mapping from values to a list of keys

License

Open Source License

Parameter

Parameter Description
map the map to reverse

Return

the reversed map

Declaration

public static <K, V> Map<V, List<K>> reverseMapping(Map<K, V> map) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    /**/* w  ww . jav  a2 s .  com*/
     * reverse a Map to give a mapping from values to a list of keys
     * @param map the map to reverse
     * @return the reversed map
     */
    public static <K, V> Map<V, List<K>> reverseMapping(Map<K, V> map) {
        Map<V, List<K>> rev = new HashMap<>();

        for (Map.Entry<K, V> e : map.entrySet()) {
            V v = e.getValue();

            if (!rev.containsKey(v)) {
                rev.put(v, new ArrayList<>());
            }

            rev.get(v).add(e.getKey());
        }

        return rev;
    }
}

Related

  1. reverseMap(Map origMap)
  2. reverseMap(Map map)
  3. reverseMap(Map keyIdMap, Map keyValueMap)
  4. reverseMapLookup(Map map, V value)
  5. reverseMapping(Map value2keys, Map map)
  6. sort(Map> dataNodes, boolean reverse)
  7. sort(Map source, boolean reverse)
  8. sortByUsedSpace(Map> dataNodes, boolean reverse)
  9. sortByValue(Map map, boolean reverse)