Java Map Invert invertMap(Map map)

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

Description

Inverts the given map from key-value mappings to value-key mappings

Note: this may have unintended results if a certain value is included in the map more than once

License

Open Source License

Parameter

Parameter Description
map map to invert
V the type of keys maintained by the given map
K the type of mapped values

Return

inverted map

Declaration

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

Method Source Code


//package com.java2s;
/*//from  w  ww. j a  va 2  s . com
 * This file is part of Commodus.
 *
 * Commodus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Commodus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Commodus.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.*;

public class Main {
    /**
     * Inverts the given map from key-value mappings to value-key mappings
     * <p>
     * Note: this may have unintended results if a certain value is included in the map more than once
     *
     * @param map map to invert
     * @param <V> the type of keys maintained by the given map
     * @param <K> the type of mapped values
     * @return inverted map
     */
    public static <V, K> Map<V, K> invertMap(Map<K, V> map) {
        Map<V, K> inverted = new HashMap<V, K>();
        for (Map.Entry<K, V> entry : map.entrySet()) {
            inverted.put(entry.getValue(), entry.getKey());
        }
        return inverted;
    }
}

Related

  1. invertedMapFrom(Map source)
  2. invertMap(final Map map)
  3. invertMap(final Map map)
  4. invertMap(Map map)
  5. invertMap(Map map)
  6. invertMap(Map map)
  7. invertMap(Map map)
  8. invertStringMap(Map input)