❮ Previous Next ❯

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-factory methods collection1

factory methods of Set interface :

javap java.util.Set
java9-factory methods collection2  
Factory methods of Map interface

javap java.util.Queue


java9-factory methods collection3

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-factory methods collection4

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-factory methods collection5

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-factory methods collection6

❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved