简体   繁体   中英

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}

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)

I want to know is there any way to do this in O(1)

You seem to be after a bidirectional map. Java does not have such datastructure in its core library.

But Google Guava library has BiMap , which seems to be what you want:

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. This is a O(1) time complexity operation.

Totally agree with @andreas , it isn't possible with HashMap .

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.

Here is how to invert a HashMap with streams API:

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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