Here you can find the source of invertMap(Map
Note: this may have unintended results if a certain value is included in the map more than once
Parameter | Description |
---|---|
map | map to invert |
V | the type of keys maintained by the given map |
K | the type of mapped values |
public static <V, K> Map<V, K> invertMap(Map<K, V> map)
//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; } }