Reverses a map (switches key and value types). - Java Collection Framework

Java examples for Collection Framework:Map

Description

Reverses a map (switches key and value types).

Demo Code


//package com.java2s;

import java.util.HashMap;

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

public class Main {
    /**/*from www  .jav  a2  s . co  m*/
     * Reverses a map (switches key and value types).
     *
     * @param <K> the key type
     * @param <V> the value type
     * @param map the map
     *
     * @return the reversed map
     */
    public static <K, V> Map<V, K> reverse(final Map<K, V> map) {
        final Map<V, K> reversed = new HashMap<V, K>(map.size());
        for (final Entry<K, V> e : map.entrySet()) {
            reversed.put(e.getValue(), e.getKey());
        }
        return reversed;
    }
}

Related Tutorials