Collection Factory Methods in Java

Method w/ ParameterDescription
List.of(E e)A generic type that can be a class or interface.
Set.of(E e)A generic type that can be a class or interface.
Map.of(K k, V v)A key-value pair of generic types that can each be a class or interface.
Map.of(Map.Entry<? extends V> entry)A Map.Entry instance where its key can be K or one of its children, and its value can be V or any of its children.

The arrival of Java 9 brings many new features to Java’s Collections API, one of which being collection factory methods. These methods allow for easy initialization of immutable collections, whether they be empty or nonempty.

Note that these factory methods are only available for the following interfaces: List, Set, and Map

List<E> Factory Method Examples

  • List immutableEmptyList = List.of();
    • Initializes an empty, immutable List.
  • List immutableList = List.of(1, 2, 3, 4, 5);
    • Initializes an immutable List with five initial elements.
  • List mutableList = new ArrayList<>(immutableList);
    • Initializes a mutable List from an immutable List.

Set<E> Factory Method Examples

  • Set immutableEmptySet = Set.of();
    • Initializes an empty, immutable Set.
  • Set immutableSet = Set.of(1, 2, 3, 4, 5);
    • Initializes an immutable Set with five initial elements.
  • Set mutableSet = new HashSet<>(immutableSet);
    • Initializes a mutable Set from an immutable Set.

Map<K, V> Factory Method Examples

  • Map immutableEmptyMap = Map.of();
    • Initializes an empty, immutable Map.
  • Map immutableMap = Map.of(1, 2, 3, 4);
    • Initializes an immutable Map with two initial key-value entries.
  • Map immutableMap = Map.ofEntries(Map.entry(1, 2), Map.entry(3, 4));
    • Initializes an immutable Map with two initial key-value entries.
  • Map mutableMap = new HashMap<>(immutableMap);
    • Initializes a mutable Map from an immutable Map.

LEAVE A REPLY

Please enter your comment!
Please enter your name here