Java Map Invert inverse(Map map)

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

Description

Generates a map with the original map's values as keys and its keys as values.

License

Open Source License

Parameter

Parameter Description
map the original map

Exception

Parameter Description
IllegalArgumentException if there are two keys with the same value in the passed map

Return

the inverted map

Declaration

public static <V, K> Map<V, K> inverse(Map<K, V> map) 

Method Source Code


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

import java.util.HashMap;
import java.util.Map;

public class Main {
    /**/*from  w w w .ja  v a 2s . c om*/
     * Generates a map with the original map's values as keys and its keys as values.
     *
     * @param map the original map
     * @return the inverted map
     * @throws IllegalArgumentException if there are two keys with the same value in the passed map
     */
    public static <V, K> Map<V, K> inverse(Map<K, V> map) {
        Map<V, K> newMap = new HashMap<>(map.size());
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (newMap.containsKey(entry.getValue())) {
                throw new IllegalArgumentException(
                        String.format("There are two keys with the value %s in the map", entry.getValue()));
            }
            newMap.put(entry.getValue(), entry.getKey());
        }
        return newMap;
    }
}

Related

  1. inverse(Map m, Map newMap)
  2. inverse(Map map)
  3. inverseGet(Map map, Object value)
  4. invert(Map map)
  5. invert(Map in)