Java 9 Factory Method for Collections: List, Set, Map

Java 9 provides new static factory methods for creating instances of collections and maps conveniently with small number of elements. In this tutorial, we’re gonna look at how to create List, Set, Map with Java 9 Factory Method for Collections.

I. List

To create a List, we use those static methods:

For example:

If we try to create list with null element, a java.lang.NullPointerException will be thrown:

Because the list created with static factory method is immutable, so if we try to add an element to list, it also throws an java.lang.UnsupportedOperationException

Solution for problems above:

II. Set

To create a Set, we use those static methods:

For example:

If we try to create set with null element, a java.lang.NullPointerException will be thrown:

Because the set created with static factory method is immutable, so if we try to add an element to set, it also throws an java.lang.UnsupportedOperationException

Solution for problems above:

III. Map
1. Map.of()

To create a Map, we use those static methods:

For example:

If we try to create Map with null value, a java.lang.NullPointerException will be thrown:

Because the map created with static factory method is immutable, so if we try to put (key,value) pair to map, it also throws an java.lang.UnsupportedOperationException

Solution for problems above:

2. Map.ofEntries()

If we wanna create a Map with more than ten mappings, there is another way: Using Map.ofEntries() method.

To use that method, we use a method for boxing keys and values, suitable for static import:

So, this is way to use them:

IV. Source Code

Run the code, the result in Console Window:

By JavaSampleApproach | March 5, 2017.

Last updated on June 29, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*