Factory methods are a special type of static methods that can be used to create unmodifiable instances of collections. It means that we can use these methods to create a list, set, and map of a small number of elements.
List.of()
The List.of() is a static factory method that provides a convenient way to create immutable lists.
Syntax
List.of(elements...)
Example
import java.util.List;
public class ListTest {
public static void main(String[] args) {
List<String> list = List.of("item 1", "item 2", "item 3", "item 4", "item 5");
for(String l : list) {
System.out.println(l);
}
}
}Output
item 1 item 2 item 3 item 4 item 5
Set.of() method
The Set.of() is a static factory method that provides a convenient way to create immutable sets.
Syntax
Set.of(elements...)
Example
import java.util.Set;
public class SetTest {
public static void main(String[] args) {
Set<String> set = Set.of("Item 1", "Item 2", "Item 3", "Item 4", "Item 5");
for(String s : set) {
System.out.println(s);
}
}
}Output
Item 5 Item 1 Item 2 Item 3 Item 4
Map.of() and Map.ofEntries() methods
The Map.of() and Map.ofEntries() are static factory methods that provide a convenient way to create immutable maps.
Syntax
Map.of(k1, v1, k2, v2) Map.ofEntries(entry(k1, v1), entry(k2, v2),...)
Example
import java.util.Map;
public class MapTest {
public static void main(String[] args) {
Map<Integer, String> map = Map.of(101, "Raja", 102, "Adithya", 103, "Jai");
for(Map.Entry<Integer, String> m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}Output
103 Jai 102 Adithya 101 Raja