When will I use the SingletonMap method from java Collections?

I don't understand why you need java Collections singletonMap ? Is this useful in multi-threaded applications?

+44
java collections map
Aug 19 '11 at 18:00
source share
5 answers

Basically, this allows you to do this:

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

instead of this:

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

which is much better if you have only one key / value pair. This situation probably does not occur very often, but singleton() and singletonList() can be quite useful.

+75
Aug 19 '11 at 18:12
source share
— -

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

+11
Aug 19 '11 at 18:05
source share

This is mainly for convenience and abstraction. Some APIs accept Collection as an argument, and it's nice to have an easy way to convert objects to Set or Map .

singletonMap() and singletonList() were introduced after singletonSet() in Java 1.3 because singletonSet() turned out to be useful.

+4
Aug 19 '11 at 18:05
source share

In addition, the SingletonMap implementation returned by Collections.singletonMap () has a smaller memory size than a regular HashMap. It should contain only two member fields: a key and a value, while the HashMap supports an internal array of Node objects and other member fields. Therefore, if you create many of these cards in memory, it would be a smart choice to use Collections.singletonMap ().

+4
Jun 23 '15 at 10:26
source share

This is another example, but I wrote this line of code:

 @Override public Map<Action, Promise<Boolean>> actOnResults() throws Exception { return Collections.singletonMap(Action.UPDATE_DATABASE, saver.save(results)); } 

pay attention to @Override . An interface, more generally, can display maps of many things; this particular instance always returns a card containing one thing. Also note that the key to the card is Enum. Thus, cards should never be large, they simply should contain the results of the actions indicated. In my real example, there are up to 5 actions, and this instance uses only one of them.

To be complete, EnumSet or EnumMap often suitable in these cases, but they are still annoyingly EnumMap compared to the code above.

0
Aug 14 '14 at
source share



All Articles