I don't understand why you would need java Collections singletonMap? Is it useful in multithreaded applications?
The singletonMap() method of java. util. Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable.
It's now clear that you can't use the Singleton class in a HashMap as a key. Even If you override the HashCode Object as a key is stored as a reference in Map.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With