Collection Factory Methods
suggest changeVersions
Java SE 9.
Introduction
The arrival of Java 9 brings many new features to Java’s Collections API, one of which is collection factory methods. These methods allow for easy initialization of immutable collections, whether they are empty or nonempty. The collection itself rejects modification; its elements are not copied or frozen. List.of, Set.of, and Map.of reject nulls. Set.of rejects duplicate elements, and Map.of rejects duplicate keys.
Note that these factory methods are only available for the following interfaces: List<E>, Set<E>, and Map<K, V>
Syntax
static <E> List<E> of()static <E> List<E> of(E e1)static <E> List<E> of(E e1, E e2)static <E> List<E> of(E e1, E e2, ..., E e9, E e10)static <E> List<E> of(E... elements)static <E> Set<E> of()static <E> Set<E> of(E e1)static <E> Set<E> of(E e1, E e2)static <E> Set<E> of(E e1, E e2, ..., E e9, E e10)static <E> Set<E> of(E... elements)static <K,V> Map<K,V> of()static <K,V> Map<K,V> of(K k1, V v1)static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2)static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, ..., K k9, V v9, K k10, V v10)static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
Parameters
| Method with parameter | Description |
|---|---|
List.of(E e) |
One element of type E. |
Set.of(E e) |
One element of type E. |
Map.of(K k, V v) |
One key-value pair. |
Map.ofEntries(Map.Entry<? extends K, ? extends V>... entries) |
Entries whose keys are K or a subtype and whose values are V or a subtype. |
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents