Java HashMap – Optimized way of appending a new value to a vector which is a value in a HashMap<String, Vector<String>>

huangapple go评论73阅读模式
英文:

Java HashMap - Optimized way of appending a new value to a vector which is a value in a HashMap<String, Vector<String>>

问题

类似于在C++中向向量追加新元素的方法:-

myHashMap[myKey].push_back(newElement); //直接将newElement添加到值向量中

在Java中我能想到的唯一方法是从哈希映射中获取向量。将新字符串追加到向量中,然后再使用新向量设置键。

myValue = myHashMap.get(myKey);
/**检查键是否存在

**/
//如果存在
myValue.add(newElement);
myHashmap.put(myKey, myValue);

第二种方法与前一种方法一样快吗?如果不是,还有其他方法吗?谢谢

英文:

A similar way to appending new element to a vector like in C++ :-

myHashMap[myKey].push_back(newElement); //push newElement to the value vector directly

The only way i can think of in Java is to get the vector from hashmap. Append the new string to the vector and then set the key again with the new vector.

myValue = myHashMap.get(myKey);
/**Check if the key exists

**/
//If exists
myValue.add(newElement);
myHashmap.put(myKey, myValue);

Is the second approach as fast as the previous and if not is there any other approach? Thanks

答案1

得分: 4

不必将向量重新放入映射中,因为在向其添加内容时已经在修改该向量。

myHashMap[myKey].push_back(newElement);

可以通过以下方式实现:

myHashMap.get(myKey)
         .add(newElement);

(假设 myHashMap.get(myKey) 不会返回 null)。


您可以在 Map 接口中使用 computeIfAbsent 来为首次处理的键构造向量对象。这更加优雅,不需要 if 块。

myHashMap.computeIfAbsent(key, k -> new Vector<>())
                .add(newElement);

该函数 (k -> new Vector<>())) 仅在 myHashMap 对于键 key 没有映射时才会执行。这样做的好处是它返回 key 的向量值,因此我们可以在其上链接 add 调用。

英文:

You do not have to put back the vector back in the map as you are already modifying the vector when adding to it.

myHashMap[myKey].push_back(newElement); 

is achieved by

myHashMap.get(myKey)
     .add(newElement);

(assuming myHashMap.get(myKey) does not return a null).


You can use computeIfAbsent in the Map interface to construct a vector object for a key processed for the first time. This is more elegant and does not require a if block.

myHashMap.computeIfAbsent(key, k -&gt; new Vector&lt;&gt;())
            .add(newElement);

The function (k -&gt; new Vector&lt;&gt;()) is only executed if the myHashMap does not have a mapping for the key key. The nice thing about this is it returns the vector value of key so that we can chain the add call on it.

答案2

得分: 2

首先,如果您关心Java中的性能,应该使用ArrayList而不是Vector。正如javadoc所说:

> 从Java 2平台v1.2开始,[Vector]被改装为实现List接口,使其成为Java Collections Framework的成员。与新的集合实现不同,Vector是同步的。如果不需要线程安全的实现,建议使用ArrayList来替代Vector

所以,假设我们正在使用Java 8(和ArrayList),对于C++代码有两个翻译版本。

版本#1。适用于Java 5+

HashMap&lt;String, ArrayList&lt;String&gt;&gt; myMap = new HashMap&lt;&gt;();
...
ArrayList&lt;String&gt; list = myMap.get(myKey);
if (list == null) {
    list = new ArrayList&lt;&gt;();
    myMap.put(myKey, list);
} 
list.add(newElement);

版本#2。适用于Java 8+

HashMap&lt;String, ArrayList&lt;String&gt;&gt; myMap = new HashMap&lt;&gt;();
...
myMap.computeIfAbsent(key, k -&gt; ArrayList&lt;&gt;()).add(newElement);

哪个更快?您需要进行测试以确保,但我认为第二个版本应该会稍微快一些,因为它避免了在put调用中的第二次哈希映射查找。

而且,一行代码比六行代码更整洁。(对于可读性可能有所不同。这取决于阅读代码的人,以及他们对Java 8+语言特性和API的熟悉程度。)

英文:

Firstly, if you care about performance in Java, use ArrayList instead of Vector. As the javadoc says:

> As of the Java 2 platform v1.2, [Vector] was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

So, assuming we are using Java 8 (and ArrayList), there are two translations for the C++ code.

Version #1. Works for Java 5+

HashMap&lt;String, ArrayList&lt;String&gt;&gt; myMap = new HashMap&lt;&gt;();
...
ArrayList&lt;String&gt; list = myMap.get(myKey);
if (list == null) {
    list = new ArrayList&lt;&gt;();
    myMap.put(myKey, list);
} 
list.add(newElement);

Version #2. Works for Java 8+

HashMap&lt;String, ArrayList&lt;String&gt;&gt; myMap = new HashMap&lt;&gt;();
...
myMap.computeIfAbsent(key, k -&gt; ArrayList&lt;&gt;()).add(newElement);

Which will be faster? You would need to test it to be sure, but I think that the second version should be a bit faster because it avoids the second hashmap lookup in the put call.

And 1 line of code is neater than 6 lines. (YMMV for readability. It depends on the person reading the code, and how familiar they are with Java 8+ language features and APIs.)

答案3

得分: 1

你可以用相同的方式在Java中实现这个功能。
myHashMap.get(key).add(newValue)
因为在哈希映射中,列表(或者你可以称之为向量)的引用被存储为值。所以修改列表的内容不会影响引用。你可以将这个引用想象成C++中向量的64位地址。

英文:

You can do this in the same way in java.
myHashMap.get(key).add(newValue)
Because in the hashmap the reference of list (or you can say it vector) is stored as value. So modifying the content of List will not influence the reference. You can imagine this reference likes 64bits address of a vector in c++.

huangapple
  • 本文由 发表于 2020年3月15日 14:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/60690480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定