Java Map Invert invertMap(Map map)

Here you can find the source of invertMap(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
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 Map invertMap(Map map) 

Method Source Code

//package com.java2s;
/*//from w ww .j a v a2  s  . c om
 *  Copyright 2001-2005 The Apache Software Foundation
 *
 *  Licensed 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.Iterator;
import java.util.Map;

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 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 Map invertMap(Map map) {
        Map out = new HashMap(map.size());
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            out.put(entry.getValue(), entry.getKey());
        }
        return out;
    }
}

Related

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