0

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

3 Answers3

4

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 -> new Vector<>())
            .add(newElement);

The function (k -> new Vector<>()) 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.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • Thanks for the quick answer. The second approach looks very clean. Didnt know chaining was possible here. One more question if you dont mind. Does get return a reference to the value or is direct modification possible only via chaining. – Priyanshu Sharma Mar 15 '20 at 07:12
  • Java is always call/pass by *value*. But the value is the *reference* (to Vector) here. So, even with *get* you can achieve the same result. – Thiyagu Mar 15 '20 at 07:14
  • Note that the second solution is only available with Java 8 and later. But it is definitely the best solution. – Stephen C Mar 15 '20 at 07:26
2

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<String, ArrayList<String>> myMap = new HashMap<>();
...
ArrayList<String> list = myMap.get(myKey);
if (list == null) {
    list = new ArrayList<>();
    myMap.put(myKey, list);
} 
list.add(newElement);

Version #2. Works for Java 8+

HashMap<String, ArrayList<String>> myMap = new HashMap<>();
...
myMap.computeIfAbsent(key, k -> ArrayList<>()).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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you. In terms of performance both will suffice. I am using Java 10 so I will go with the second approach since it looks cleaner. I was confused because I didn't know that a pointer will be returned. This thread and [this thread](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) cleared my confusion. – Priyanshu Sharma Mar 15 '20 at 08:11
1

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++.

  • Thank you. Much appreciated. Just found out about the pass-by-value and pass-by-reference confusion in java. Helped me understand about this problem. – Priyanshu Sharma Mar 15 '20 at 07:38