Reverses a map (switches key and value types). - Java java.util

Java examples for java.util:Map Operation

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 {
    /**/*  w w w  . j a va  2 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