As with List.of()
, in Java 9, the Set.of()
factory method can be used to create an unmodifiable set of specified elements.
Here is a simple example:
package org.kodejava.util;
import java.util.Set;
public class SetOfExample {
public static void main(String[] args) {
Set<String> names = Set.of("Rosa", "John", "Mary", "Alice");
for (String name : names) {
System.out.println(name);
}
}
}
Output:
John
Rosa
Alice
Mary
In this example, the Set.of("Rosa", "John", "Mary", "Alice")
statement creates an unmodifiable set of strings containing “Rosa”, “John”, “Mary”, and “Alice”. The resulting set is unmodifiable, so attempting to add, update, or remove elements from it will throw an UnsupportedOperationException
.
If you try to create a Set
by providing a duplicate elements, an IllegalArgumentException
will be thrown. A Set
is a type of collection container that cannot have duplicate values in it.
Note that the Set.of()
method doesn’t accept null
values. If you try to insert a null
value, it will throw a NullPointerException
. If you add a null
value using the add()
method UnsupportedOperationException
will be thrown.
Set.of()
is overloaded similarly to List.of()
, allowing you to create a set with varying numbers of elements. The below examples demonstrate the use of Set.of() with different numbers of arguments:
Set<String> a = Set.of(); // An empty set
Set<String> b = Set.of("One"); // A set with one element
Set<String> c = Set.of("One", "Two"); // A set with two elements
// ...
Set<String> j = Set.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"); // A set with ten elements
If you need to create a set with more than 10 elements, Set.of()
offers an overloaded version that accepts an array or varargs:
Set<String> set = Set.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven");
Remember that sets created with Set.of()
are unmodifiable. Attempting to add, remove or change an element in these sets after their creation causes an UnsupportedOperationException
.
Also, Set.of()
doesn’t allow duplicate or null
elements. If you pass duplicate or null
values, it will throw IllegalArgumentException
and NullPointerException
respectively.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024