Factory method is a special type of static method that can be used to create unmodifiable collection instances . This means that we can use these methods to create lists, sets and maps containing a small number of elements.
List.of() is a static factory method that provides a convenient way to create immutableList.
<strong>List.of(elements...)</strong>
import java.util.List; public class ListTest { public static void main(String[] args) { <strong>List<String></strong> list =<strong> List.of</strong>("item 1", "item 2", "item 3", "item 4", "item 5"); for(String l : list) { System.out.println(l); } } }
<strong>item 1 item 2 item 3 item 4 item 5</strong>
##Set.of() method
Set.of() is a static factory method that provides a convenient way to create immutable sets.
Syntax<strong>Set.of(elements...) </strong>
import java.util.Set; public class SetTest { public static void main(String[] args) { <strong>Set<String></strong> set = <strong>Set.of</strong>("Item 1", "Item 2", "Item 3", "Item 4", "Item 5"); for(String s : set) { System.out.println(s); } } }
<strong>Item 5 Item 1 Item 2 Item 3 Item 4</strong>
##Map.of() and Map. ofEntries() method
and Map.ofEntries() are static factory methods that provide a convenient way to create Immutable Mapping. Syntax
<strong>Map.of(k1, v1, k2, v2) Map.ofEntries(entry(k1, v1), entry(k2, v2),...)</strong>
import java.util.Map; public class MapTest { public static void main(String[] args) { <strong>Map<Integer, String></strong> map = <strong>Map.of</strong>(101, "Raja", 102, "Adithya", 103, "Jai"); for(<strong>Map.Entry<Integer, String></strong> m : map.<strong>entrySet()</strong>) { System.out.println(m.getKey() + " " + m.getValue()); } } }
<strong>103 Jai 102 Adithya 101 Raja</strong>
The above is the detailed content of What factory methods have been added for collections in Java 9?. For more information, please follow other related articles on the PHP Chinese website!