When would I use java Collections singletonMap method?

Basically, it allows you to do this:

callAPIThatTakesAMap(Collections.singletonMap(key, value));

rather than this:

Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key, value);
callAPIThatTakesAMap(m);

which is much nicer when you only have a single key/value pair. This situation probably does not arise very often, but singleton() and singletonList() can quite frequently be useful.


It is useful if you need to pass a map to some general code (as a parameter, or as a result from a method) and you know that in this particular case -- but perhaps not in other cases that pass map to the same general code -- the map you want to pass has only a single key. In that case, the SingletonMap is more efficient than a full-blown map implementation, and also more convenient for the programmer because everything you need to say can be said in the constructor.


Also, a SingletonMap implementation returned by Collections.singletonMap() has a smaller memory footprint than a regular HashMap. It only has to contain two member fields: the key and the value, whereas a HashMap maintains an internal array of Node objects plus other member fields. So if you are creating a lot of these maps in memory, it would be a prudent choice to use Collections.singletonMap().