Java Set.of() Example

By Arvind Rai, January 31, 2020
The Set.of is a static factory method that creates immutable Set introduced in Java 9. The instance created by Set.of has following characteristics.
1. The Set obtained from Set.of is unmodifiable. We cannot add, delete elements to it. We can also not update the reference of object at any index in the unmodifiable Set.
2. An unmodifiable Set is immutable only when it contains immutable objects. Immutable Set is automatically thread-safe. It also consumes much less memory than the mutable one.
3. If we try to change unmodifiable Set, it will throw UnsupportedOperationException.
4. The immutable Set can be used to improve performance and save memory.
5. The unmodifiable Set does not allow duplicate values and null values at creation time.
6. The iteration order of Set elements are unspecified and may change.
7. The Set.of has following method signature.
static <E> Set<E> of​(E... elements) 
Here on this page we will create immutable Set using Set.of method.

Creating Immutable Set using Set.of

Find the examples to create immutable Set using Set.of method.
Example-1: Find immutable Set with string object.
SetOf1.java
import java.util.Set;
public class SetOf1 {
  public static void main(String[] args) {
	Set<String> imtSet = Set.of("PP", "QQ", "RR");
	imtSet.forEach(s -> System.out.println(s));
  }
} 
If we try to add element in immutable Set, we will get error.
imtSet.add("SS"); 
The error will be as following.
Exception in thread "main" java.lang.UnsupportedOperationException 
Example-2: Find immutable Set with immutable Set objects.
SetOf2.java
import java.util.Set;
public class SetOf2 {
  public static void main(String[] args) {
	Set<String> imtSet1 = Set.of("P1", "Q1", "R1");
	Set<String> imtSet2 = Set.of("P2", "Q2", "R2");	
	
	Set<Set<String>> imtFinalSet = Set.of(imtSet1, imtSet2);
	System.out.println(imtFinalSet);
  }
} 

An unmodifiable Set containing the mutable objects is not the immutable Set. To understand this, find the example where we change the mutable Set value as element and there will also be change in unmodifiable Set values.
SetOf3.java
import java.util.HashSet;
import java.util.Set;
public class SetOf3 {
  public static void main(String[] args) {
	Set<String> set1 = new HashSet<>();
	set1.add("P1");
	set1.add("Q1");
	set1.add("R1");
	Set<String> set2 = new HashSet<>();
	set2.add("P2");
	set2.add("Q2");
	set2.add("R2");	
	
	Set<Set<String>> finalSet = Set.of(set1, set2);
	System.out.println(finalSet);
	
	set1.add("SS");
	System.out.println(finalSet);
  }
} 
Output
[[Q1, P1, R1], [R2, Q2, P2]]
[[Q1, SS, P1, R1], [R2, Q2, P2]] 

Example-3: Find the immutable Set containing objects of custom immutable class.
SetOf4.java
import java.util.Set;
public class SetOf4 {
  public static void main(String[] args) {
	Student s1 = new Student(24, "Mahesh");
	Student s2 = new Student(25, "Suresh");
	Student s3 = new Student(26, "Nilesh");

	Set<Student> imtSet = Set.of(s1, s2, s3);
	imtSet.forEach(s -> System.out.println(s.getName()));
  }
}

final class Student {
  final private int age;  
  final private String name;
  public Student(final int age, final String name) {
      this.age = age;
      this.name = name;
  }
  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }
  @Override
  public boolean equals(Object ob) {
      return name.equals(((Student)ob).name) &&
    	  age == ((Student)ob).age;
  }
  @Override
  public int hashCode() {
      int hash = 13;
      hash = (31 * hash) + (null == name ? 0 : name.hashCode());
      return hash;
  }  
} 

Set.of() vs Collections.unmodifiableSet()

The Set returned by Set.of() and Collections.unmodifiableSet() both are unmodifiable but there is difference that Collections.unmodifiableSet() returns an unmodifiable view of the specified Set. If we perform add, update or delete operation on source Set specified to Collections.unmodifiableSet() then the unmodifiable Set returned by this method will also change.
UnmodifiableSetTest.java
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class UnmodifiableSetTest {
  public static void main(String[] args) {
	Set<String> set = new HashSet<>();
	set.add("P1");
	set.add("Q1");
	set.add("R1");
	
	Set<String> unmodSet = Collections.unmodifiableSet(set);
	System.out.println(unmodSet);
	
	set.add("S1");
	System.out.println(unmodSet);
  }
} 
Output
[Q1, P1, R1]
[Q1, P1, S1, R1] 

References

Java doc: Set
Creating Immutable Sets
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us