Set.of() example in Java

In this post, I will be sharing the Java Set.of() example. This method was introduced in Java 9. Let's dive deep into the topic:

Read Also: How to Iterate HashSet in Java with Examples

Java Set.of() example

Syntax


According to Oracle docs, the Java Set.of() method has the following syntax:

 static <E> Set<E> of(E... elements)


Returns


It returns an immutable set containing an arbitrary number of elements.

1. Simple Set.of() Example


Simple example of Set.of() method is shown below:

import java.util.Set;
public class SetOfExample {
    public static void main(String args[]) {
      Set<String> setObj = Set.of("Alive","is","Awesome");
      setObj.forEach( s -> System.out.println(s));
    }
}


Output:
is
Alive
Awesome


2. Custom Immutable Class Set.of() Example


import java.util.Set;
public class SetOfExample2
{
    public static void main(String args[])
    {
        Employee e1 = new Employee(1, "Subham Mittal");
        Employee e2 = new Employee(2, "John");
        Employee e3 = new Employee(3, "Jack");
        Set<Employee> immSet = Set.of(e1, e2, e3);
        immSet.forEach(e -> System.out.println(e.getEmpName()));
    }
}

final class Employee
{
    final private int empId;
    final private String empName;
    public Employee(int empId, String empName)
    {
        this.empId = empId;
        this.empName = empName;
    }
    public int getEmpId()
    {
        return empId;
    }
    public String getEmpName()
    {
        return empName;
    }
}


Output:
Subham Mittal
Jack
John


Set.of() method: Important Points to Remember


1. The Set obtained from the Set.of() method is unmodifiable, in simple words, we can not add and delete elements to it. If we try to add or delete elements to it, then it will throw an UnsupportedOperationException as shown below in the code:

import java.util.Set;
public class SetOfExample {
    public static void main(String args[]) {
      Set<String> setObj = Set.of("Alive","is","Awesome");
      setObj.add("Be in present");
      setObj.forEach( s -> System.out.println(s));
    }
}


Output:
Exception in thread "main" java.lang.UnsupportedOperationException


2. Immutable Sets do not allow null elements. If you try to do so, then you will get NullPointerException.

3. Set does not allow duplicate elements. Any attempt to add duplicate elements will result in IllegalArgumentException.

4. As we all know, the iteration order of Set elements is unspecified and is subject to change.

5. Immutable Set is serializable if all the elements are serializable.

That's all for today. Please mention in the comments if you have any questions related to the Java Set.of() example.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry