Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Factory methods in Collections

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,

javap java.util.List

java9-1



factory methods of Set interface :

javap java.util.Set

java9-1


Factory methods of Map interface

javap java.util.Queue

java9-1


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:

java9-1


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:

java9-1


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:

java9-1

About the Author



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






 PreviousNext