Here you can find the source of reverseMap(Map
Parameter | Description |
---|---|
original | The original map to reverse. |
public static <K, V> HashMap<V, K> reverseMap(Map<K, V> map)
//package com.java2s; /* Copyright (C) 2009 Mobile Sorcery AB //from w w w . j ava 2 s . c om This program is free software; you can redistribute it and/or modify it under the terms of the Eclipse Public License v1.0. This program 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 Eclipse Public License v1.0 for more details. You should have received a copy of the Eclipse Public License v1.0 along with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html */ import java.util.HashMap; import java.util.Map; public class Main { /** * Reverses a map into a {@link HashMap}. * @param original The original map to reverse. * @return A reverse map. If the original map contains several * keys with the same value an {@link IllegalArgumentException} * is thrown. */ public static <K, V> HashMap<V, K> reverseMap(Map<K, V> map) { HashMap<V, K> result = new HashMap<V, K>(); for (Map.Entry<K, V> entry : map.entrySet()) { V key = entry.getValue(); if (result.containsKey(key)) { throw new IllegalArgumentException("Key already present."); } result.put(key, entry.getKey()); } return result; } }