Tiny note about Collections#singleton method
Tiny note about Collections#singleton
Sometimes you want to create either List, Map (or maybe Set) object which only contains one value due to either API requires this sort of type as its parameter or some other reasons. For example, let’s say the API you are about to use requires
Map object as a parameter and you know that this
Map will contain only one key-value pair. You could create a new instance and pass the instance to it of course, but it will look something like this:
String id = "some id"; Map<String, String> parameter = new HashMap<String, String>; parameter.put("id", id); Api.get(url).parameter(parameter);
which may look common, but you may not think it looks the best.
In that case, you can make use of
Collections#singletonMap(K, V), and write just like this:
In similar situations, you can do the same thing for
Set classes as well.
Above is a start for me to look up and know about this useful
Collections util method; I found it by chance. We gotta make use of them because it’s there to make our life easier.
Check out the oracle official javadoc and the links below to know more about them.