Java Map Reverse reverseMap(Map map)

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

Description

Reverses a map into a HashMap .

License

Open Source License

Parameter

Parameter Description
original The original map to reverse.

Return

A reverse map. If the original map contains several keys with the same value an is thrown.

Declaration

public static <K, V> HashMap<V, K> reverseMap(Map<K, V> map) 

Method Source Code

//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;
    }
}

Related

  1. reverseLabelMap(Map labelMap)
  2. reverseMap(List listSeq)
  3. reverseMap(Map map)
  4. reverseMap(Map map)
  5. reverseMap(Map map)
  6. reverseMap(Map map)
  7. reverseMap(Map origMap)
  8. reverseMap(Map map)
  9. reverseMap(Map keyIdMap, Map keyValueMap)