Java Map Invert invertMap(final Map map)

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

Description

Inverts the supplied map returning a new HashMap such that the keys of the input are swapped with the values.

License

Apache License

Parameter

Parameter Description
K the key type
V the value type
map the map to invert, may not be null

Exception

Parameter Description
NullPointerException if the map is null

Return

a new HashMap containing the inverted data

Declaration

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

Method Source Code

//package com.java2s;
/*//from ww w .  ja v  a2 s  .c  o m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.HashMap;

import java.util.Map;
import java.util.Map.Entry;

public class Main {
    /**
     * Inverts the supplied map returning a new HashMap such that the keys of
     * the input are swapped with the values.
     * <p>
     * This operation assumes that the inverse mapping is well defined.
     * If the input map had multiple entries with the same value mapped to
     * different keys, the returned map will map one of those keys to the
     * value, but the exact key which will be mapped is undefined.
     *
     * @param <K>  the key type
     * @param <V>  the value type
     * @param map  the map to invert, may not be null
     * @return a new HashMap containing the inverted data
     * @throws NullPointerException if the map is null
     */
    public static <K, V> Map<V, K> invertMap(final Map<K, V> map) {
        final Map<V, K> out = new HashMap<V, K>(map.size());
        for (final Entry<K, V> entry : map.entrySet()) {
            out.put(entry.getValue(), entry.getKey());
        }
        return out;
    }
}

Related

  1. invert(Map map)
  2. invert(Map map, String prefix)
  3. invert(Map map)
  4. invertedMapFrom(Map source)
  5. invertMap(final Map map)
  6. invertMap(Map map)
  7. invertMap(Map map)
  8. invertMap(Map map)
  9. invertMap(Map map)