简体   繁体   English

复制一个 HashMap<K,V> 到另一个 HashMap<V,K> 在 O(1) 复杂度 (JAVA)

[英]Copy one HashMap<K,V> to another HashMap<V,K> in O(1) complexity (JAVA)

Suppose I have a HashMap<String,String> which have elements {one=1, two=2, three=3, four=4} and I want to create another HashMap<String,String> whose elements would be {1=one, 2=two, 3=three, 4=four}假设我有一个HashMap<String,String>有元素{one=1, two=2, three=3, four=4}并且我想创建另一个HashMap<String,String>其元素将是{1=one, 2=two, 3=three, 4=four}

One approach is一种方法是

HashMap<String,String> map1 = new HashMap<String,String>();

map1.put("one",1);
map1.put("two",2);
map1.put("three",3);
map1.put("four",4);

HashMap<String,String> map2 = new HashMap<String,String>();

  for(String s : map.keySet())
  {
    map2.put(map.get(s),s);
  }

But it has time complexity O(N)但它的时间复杂度为O(N)

I want to know is there any way to do this in O(1)我想知道有没有办法在O(1) 中做到这一点

You seem to be after a bidirectional map.你似乎在追求双向地图。 Java does not have such datastructure in its core library. Java 在其核心库中没有这样的数据结构。

But Google Guava library has BiMap , which seems to be what you want:但是谷歌番石榴库BiMap ,这似乎是你想要的:

BiMap<String, String> biMap = HashBiMap.create();

biMap.put("key1", "value1");
biMap.put("key2", "value2");

BiMap<String, String> inverse = biMap.inverse();

String key1 = inverse.get("value1"); // key1

Here the BiMap.inverse() method returns a view of the original map.这里BiMap.inverse()方法返回原始地图的视图 This is a O(1) time complexity operation.这是一个O(1)时间复杂度操作。

Totally agree with @andreas , it isn't possible with HashMap .完全同意@andreasHashMap不可能。

You might want to use BitMap as suggested by @fps but if have to do it with HashMap you don't really have many options.你可能想使用位图所建议@fps但如果有HashMap来做到这一点,你真的没有很多选择。

Here is how to invert a HashMap with streams API:以下是如何使用流 API 反转HashMap

Map<String,String> map = Map.of("one","1","two","2","three","3")

Map<String,String> reversedMap = map.entrySet()
                                .stream()
                                .map(es -> Map.entry(es.getValue(),es.getKey()))
                                .collect(Collectors.toMap(es -> es.getKey(), es->es.getValue()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM