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