Quick way to create List, Set and Map
Java 9 introduced of() static methods in List, Map and Set interfaces. This method will help us to create collection easily. I got surprised to see this method, it is lot easier to use and easier to remember and less verbose. Lets see some examples of using this method.
Iterator on this list will give us the same order in which we inserted. Before java 9 we have only option to create list like this, is using Arrays.asList method. In the List interface you will see multiple overloaded of() methods, each of them takes variable number of parameters. below is the list;
There are eleven overloaded methods to handle up to ten input parameters and twelfth one takes ‘varargs’. of() is not just for List, same kind of overloaded methods are available in Set and Map as well. Except in Map there is no ‘varargs’ method.
Note that if you pass duplicate object into set then it throws IllegalArgumentException, because in set, duplicates are not allowed.
See, how easy it is to create map objects. We need to pass key and values like normal parameters to the of() method. You can also create Map with entry objects using ofEntries() method.
Duplicate keys are not allowed in Map, it will throw IllegalArgumentException.
This method creates immutable collection means; once created, no element can be added, removed or replaced and no nulls are allowed when creating the collection object.