映射中的值可能不是唯一的。但是,如果它们是(在您的情况下),则可以按照您在问题中所写的内容进行操作,并创建将其转换的通用方法:
private static <V, K> Map<V, K> invert(Map<K, V> map) { Map<V, K> inv = new HashMap<V, K>(); for (Entry<K, V> entry : map.entrySet()) inv.put(entry.getValue(), entry.getKey()); return inv;}Java 8:
public static <V, K> Map<V, K> invert(Map<K, V> map) { return map.entrySet() .stream() .collect(Collectors.toMap(Entry::getValue, Entry::getKey));}用法示例:
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("Hello", 0); map.put("World!", 1); Map<Integer, String> inv = invert(map); System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"}旁注:该
put(.., ..)方法将返回键的“旧”值。如果它不为null,则可能抛出
new IllegalArgumentException("Mapvalues must be unique")或类似的东西。


