In this post, We will talk and learn about Java 9 Collection Factory Methods Example with a demo project
- Java 9 has added simple ways to create immutable Collections without null values by providing a set of <Collection>.of methods.
- The created collection should not have null values and should not be modified later else it will throw java.lang.NullPointerException Or java.lang.UnsupportedOperationException at runtime.
- Java 9 Collection Framework updated to include static factory methods for List, Set and Map interface. These methods are very useful to create unmodifiable objects of collections with a small number of elements.
Java 9 Map Interface ofEntries() Method Example
- In Java 9, in addition to static Map.of() methods, Map interface includes one more static factory method Map.ofEntries(Entry<? extends K, ? extends V>… entries). This function is used to create a map of Map.Entry instances.
CollectionFactoryMethodsTest.java
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 28 29 30 31 32 33 34 35 36 |
import java.util.List; import java.util.Map; import java.util.Set; /** * @author KK JavaTutorials *Java 9 Collection Factory Methods Example */ public class CollectionFactoryMethodsTest { public static void main(String[] args) { /* List<String> list = new ArrayList<>(); list.add("KK"); list.add("PK"); list.add("SK"); list.add("MK");*/ List<String> list = List.of("KK", "PK", "SK", "MK"); list.forEach(System.out::println); //list.add("JJ"); Set<String> set = Set.of("KK", "PK", "SK", "MK"); set.forEach(System.out::println); System.out.println("=================================="); Map<Integer,String> empIdNameMap1 = Map.of(1234, "KK", 78778, "PK"); empIdNameMap1.forEach((key,value)->System.out.println(key+"\t"+value)); System.out.println("=================================="); Map.Entry<Integer, String> entry1 = Map.entry(1233445, "kkklklfkl"); Map.Entry<Integer, String> entry2 = Map.entry(12335786, "jdgdjgg"); Map.Entry<Integer, String> entry3 = Map.entry(1284886, "jkdlg"); Map<Integer,String> empIdNameMap2 = Map.ofEntries(entry1,entry2,entry3); empIdNameMap2.forEach((key,value)->System.out.println(key+"\t"+value)); } } |
If you run CollectionFactoryMethodsTest.java as Java Application then it will give the below output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
KK PK SK MK MK KK PK SK ================================== 78778 PK 1234 KK ================================== 1233445 kkklklfkl 12335786 jdgdjgg 1284886 jkdlg |
That’s all about Java 9 Collection Factory Methods Example
You May Also Like:
Java 9 Jshell Tutorial
Java 9 private Methods in Interfaces
Java 9 Try with Resource Enhancement
Java 9 @SafeVarargs Annotation
Java 9 Stream API improvements
If you have any feedback or suggestion please feel free to drop in below comment box.