When would I use java Collections singletonMap method?

user710818 picture user710818 · Aug 19, 2011 · Viewed 54.5k times · Source

I don't understand why you would need java Collections singletonMap? Is it useful in multithreaded applications?

Answer

Michael Borgwardt picture Michael Borgwardt · Aug 19, 2011

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.