Java 9 Set.of() Method - Create Immutable Set Example

In this post, I show you how to create an immutable Set using Java 9 provided Set.of() static factory method.

Create Immutable Set

Use Set.of() static factory methods to create immutable sets. It has following different overloaded versions –
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 e3)
static <E> Set<E>   of(E e1, E e2, E e3, E e4)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5, E e6)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
static <E> Set<E>   of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
//varargs
static <E> Set<E>   of(E... elements)
The Set instances created by these methods have the following characteristics:
  1. These sets are immutable. Elements cannot be added, removed, or replaced in these sets. Calling any mutator method (i.e. add, addAll, clear, remove, removeAll, replaceAll) will always cause UnsupportedOperationException to be thrown.
  2. They do not allow null elements. Attempts to add null elements result in NullPointerException.
  3. They are serializable if all elements are serializable.
  4. Set do not allow duplicate elements as well. Any duplicate element passed will result in IllegalArgumentException.
  5. The iteration order of set elements is unspecified and is subject to change.

Create Immutable Set Example - Java 9 Set.of() Method

Let's use Set.of() static factory methods to create immutable sets.
package net.javaguides.corejava.java9;

import java.util.Set;

/**
 * Java 9 Immutable Set Example
 * 
 * @author Ramesh Fadatare
 *
 */
public class ImmutableSetExample {

    public static void main(String[] args) {

        // Creating Immutable Set
        Set < String > fruits = Set.of("Banana", "Apple", "Mango", "Orange");
        fruits.forEach(e - > System.out.println(e));

        // You can't add Elements Immutable Set
        // fruits.add("Strawberry"); // Exception in thread "main"
        // java.lang.UnsupportedOperationException

        // Example 2
        Set < String > set = Set.of("A", "B", "C", "D");
        set.forEach(e - > System.out.println(e));
    }
}
Output:
Banana
Apple
mango
orange
A
B
C
D

Related Java 9 Posts


Comments