I have a map like this with several million entries:
private final Map<String, SomeItem> tops = new HashMap<>();
I need to get list of values, which could be done by calling java.util.Map values()
method.
Is Collection
of values created every time I call values()
method or is it pre-computed from performance perspective?
As my Map
has several millions elements, I do not want to create new list object every time values()
is called.
Advertisement
Answer
Below is the copied implementation of Map.values()
in java.util.HashMap
:
public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; }
This clearly shows that the value collection isn’t created unless necessary. So, there should not be additional overhead caused by calls to values()