英文:
Copy one HashMap<K,V> to another HashMap<V,K> in O(1) complexity (JAVA)
问题
假设我有一个 HashMap<String, String>
,其中包含元素 {one=1,two=2,three=3,four=4}
,我想创建另一个 HashMap<String, String>
,其元素将为 {1=one,2=two,3=three,4=four}
。
一种方法是:
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);
}
但这个方法的时间复杂度为 O(N)。
我想知道是否有办法以 O(1) 的时间复杂度实现这一点。
英文:
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)
答案1
得分: 2
你似乎在寻找一个双向映射。Java核心库中没有这样的数据结构。
但是Google Guava库有一个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
在这里,BiMap.inverse()
方法返回原始映射的视图。这是一个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.
答案2
得分: 0
完全同意@andreas,使用HashMap是不可能的。
你可能想要使用BitMap,正如@fps所建议的,但如果必须使用HashMap,你真的没有太多的选择。
以下是如何使用流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()));
英文:
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()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论