You can provide an initial capacity in the HashMap
constructor:
Map<String> map = new HashMap<>(1);
It looks like that is genuinely obeyed in the implementation I'm looking at, but I can easily imagine some implementations having a "minimum viable capacity" such as 16. You'd have to be creating a large number of maps for this to really be an issue.
On the other hand, if you really only need a single-entry map and you're in a performance-sensitive situation, I would suggest you might not want to use HashMap
at all. It wouldn't be hard to write a Map
implementation which knew that it always had exactly one entry (which would presumably be provided on construction). If your code depends on having a HashMap
rather than a Map
, you should check whether you really want that top be the case.