In Java 9, factory methods are introduced for collections API. Below are examples.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//Example import java.util.List; import java.util.Map; import java.util.Set; public class CollectionsFactoryMethods { public static void main(String[] args) { /* * List factory method */ List<String> numberList = List.of("One", "Two", "Three"); System.out.println(numberList); /* * Set factory method */ Set<String> numberSet = Set.of("One", "Two", "Three"); System.out.println(numberSet); /* * Map factory method */ Map<String, String> numberMap = Map.of("1", "One", "2", "Two", "3", "Three"); System.out.println(numberMap); } } |
Output:
1 2 3 |
[One, Two, Three] [One, Two, Three] {3=Three, 2=Two, 1=One} |