Java反转映射

use*_*818 27 java map invert

我需要创建逆映射 - 选择唯一值并为它们找到键.似乎只有迭代所有键/​​值对的方法,因为entrySet返回的set值不是唯一的?谢谢.

dac*_*cwe 37

地图中的值可能不是唯一的.但是如果它们(在你的情况下)你可以按照你在问题中写的那样做,并创建一个通用方法来转换它:

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;
}
Run Code Online (Sandbox Code Playgroud)

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));
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

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!}"
}
Run Code Online (Sandbox Code Playgroud)

旁注:该put(.., ..)方法将返回键的"旧"值.如果它不是null,你可以扔一个new IllegalArgumentException("Map values must be unique")或类似的东西.

  • 在Java 8示例中,您可以对键和值使用方法引用(即`toMap(Entry :: getValue,Entry :: getKey)`),而不是使用一个方法引用和一个lambda. (6认同)

Rha*_*aun 10

看看Google Guava BiMap.

用法示例

Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");

Map<String, Integer> inverted = HashBiMap.create(map).inverse();
Run Code Online (Sandbox Code Playgroud)


mik*_*lly 5

要在Java 8中获取给定映射的倒排形式:

public static <K, V> Map<V, K> inverseMap(Map<K, V> sourceMap) {
    return sourceMap.entrySet().stream().collect(
        Collectors.toMap(Entry::getValue, Entry::getKey,
           (a, b) -> a) //if sourceMap has duplicate values, keep only first
        );
}
Run Code Online (Sandbox Code Playgroud)

用法示例

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(1, "one");
map.put(2, "two");

Map<String, Integer> inverted = inverseMap(map);
Run Code Online (Sandbox Code Playgroud)