DEV Community

loizenai
loizenai

Posted on

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

https://grokonez.com/java/java-9/java-9-factory-method-for-immutable-collections-list-set-map

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 empty list
static  List of()
// for list containing one element
static  List of(E e1)
// for list containing two element
static  List of(E e1, E e2)
// ...
// for list containing an arbitrary number of elements
static  List of(E... elements)

For example:


List immutableList = List.of();
immutableList = List.of("one", "two", "three");

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


List immutableList = List.of("one", "two", "three", null);

Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:221)
    at java.base/java.util.ImmutableCollections$ListN.(ImmutableCollections.java:233)
    at java.base/java.util.List.of(List.java:859)

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

More at:

https://grokonez.com/java/java-9/java-9-factory-method-for-immutable-collections-list-set-map

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

Top comments (0)