Hii frnds, now I am going to present some factory methods in collections. JAVA 9 have added some more new factory methods.
Factory methods of List interface,
factory methods of Set interface :
Factory methods of Map interface
Now let’s see an example;
FactoryTest.java
import java.util.*; class FactoryTest { public static void main(String[] args) { List< String> l=new ArrayList< >(); l.add("Nilana"); l.add("Dolagobinda"); l.add("Basu"); l.add("Rupeli"); System.out.println(l); } }
Output:
In the above program, we used add() method to insert elements in ArrayList. But in JAVA 9 there is a static method, that is List.of() that we will use for inserting elements, then you will feel how the code complexity is reduced. Let’s see:
FactoryTest.java
import java.util.*; class FactoryTest { public static void main(String[] args) { List< String> l=List.of("Nilana","Dolagobinda","Basu","Rupeli"); System.out.println(l); } }
Output:
Let’s see another example by taking Map interface.
import java.util.*; class FactoryTest { public static void main(String[] args) { Map< String,Integer> m=Map.of("Nilana",1,"Dolagobinda",2,"Basu",3,"Rupeli",4); System.out.println(m); } }
Output:
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc