Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use java Collections singletonMap method?

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

like image 201
user710818 Avatar asked Aug 19 '11 18:08

user710818


People also ask

Where is collections singletonMap method used?

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.

Can we create a HashMap key Singleton?

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.


2 Answers

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.

like image 68
Michael Borgwardt Avatar answered Oct 09 '22 10:10

Michael Borgwardt


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.

like image 36
hmakholm left over Monica Avatar answered Oct 09 '22 10:10

hmakholm left over Monica