Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当一种类型是一组整数时,如何反转映射的值_Java_Dictionary - Fatal编程技术网

Java 当一种类型是一组整数时,如何反转映射的值

Java 当一种类型是一组整数时,如何反转映射的值,java,dictionary,Java,Dictionary,例如,如何从以下内容中反转键和值数据类型: TreeMap<Set<Integer>, Integer> TreeMap ……在这方面: TreeMap<Integer, Set<Integer>> TreeMap 迭代条目集,并将它们反向放入新的树状图中。以下通用方法将反转每个贴图 public static <K, V> TreeMap<V, K> reverse(TreeMap<K, V> m

例如,如何从以下内容中反转键和值数据类型:

TreeMap<Set<Integer>, Integer>    
TreeMap
……在这方面:

TreeMap<Integer, Set<Integer>>
TreeMap

迭代条目集,并将它们反向放入新的树状图中。以下通用方法将反转每个贴图

public static <K, V> TreeMap<V, K> reverse(TreeMap<K, V> map) {
    TreeMap<V, K> result = new TreeMap<V, K>();

    for (Entry<K, V> e : map.entrySet())
        result.put(e.getValue(), e.getKey());
    return result;
}

元组
{1,2}
丢失,因为值2多次出现

如果您使用的是Java8,您可以:

TreeMap<Set<Integer>, Integer> map = ....;
Map<Integer, Set<Integer>> result = 
       map.entrySet()
          .stream()
          .map(entry -> new AbstractMap.SimpleEntry(entry.getValue(), entry.getKey())
          .collect(Collectors.toMap());
TreeMap映射=。。。。;
映射结果=
map.entrySet()
.stream()
.map(entry->newAbstractMap.SimpleEntry(entry.getValue(),entry.getKey())
.collect(Collectors.toMap());

Map
s不容易可逆,这是正确的。 反转地图可能不起作用。 在
映射中
键显然是唯一的,但值没有这样的约束

我不知道你面临的问题是什么,但听起来好像有更好的设计来解决它

也许您应该使用
BiMap
? 它本质上是一个双向映射,其中“键”和“值”都是唯一的。它允许从键和值进行有效的查找


Java没有内置的
BiMap
,但是and有。

所以你想要一个像:TreeMap这样的数据结构吗?换句话说,让它成为TreeMap你必须确定这些值是唯一的。@Robert-更新你的问题,让它包括输出应该是什么?我可以对一组整数使用迭代器吗?我可以做些什么吗g像这个Map Map=new TreeMap();Set temp=Map.keySet();Map newMap=new TreeMap();Iterator in=temp.Iterator();while(in.hasNext()){Set temps=in.next();Integer temp2=Map.get(temp);newMap.put(temp2,temps);}我迭代了映射的条目集。条目集将映射中的键/值对存储为元组。
{2=2}
TreeMap<Set<Integer>, Integer> map = ....;
Map<Integer, Set<Integer>> result = 
       map.entrySet()
          .stream()
          .map(entry -> new AbstractMap.SimpleEntry(entry.getValue(), entry.getKey())
          .collect(Collectors.toMap());