Factory Methods in Java 9

Last updated on Dec 23 2022
Prabhas Ramanathan

Java 9 Collection library includes static factory methods for List, Set and Map interface. These methods are useful to create small number of collection.
Suppose, if we want to create a list of 5 elements, we need to write the following code.

Table of Contents

Java List Example

1. import java.util.ArrayList; 
2. import java.util.List; 
3. public class FactoryMethodsExample { 
4. public static void main(String[] args) { 
5. List<String> list = new ArrayList<>(); 
6. list.add("Java"); 
7. list.add("JavaFX"); 
8. list.add("Spring"); 
9. list.add("Hibernate"); 
10. list.add("JSP"); 
11. for(String l : list){ 
12. System.out.println(l); 
13. } 
14. } 
15. }

Output:
Java
JavaFX
Spring
Hibernate
JSP
In the above code, add method is called repeatedly for each list element, while in Java 9 we can do it in single line of code using factory methods.

Factory Methods for Collection

Factory methods are special type of static methods that are used to create unmodifiable instances of collections. It means we can use these methods to create list, set and map of small number of elements.
It is unmodifiable, so adding new element will throw java.lang.UnsupportedOperationException
Each interface has it’s own factory methods, we are listing all the methods in the following tables.

Factory Methods of List Interface

Modifiers Methods Description
static <E> List<E> Of() It It returns an immutable list containing zero elements.
static <E> List<E> of(E e1) It It returns an immutable list containing one element.
static <E> List<E> of(E… elements) It It returns an immutable list containing an arbitrary number of elements.
static <E> List<E> of(E e1, E e2) It It returns an immutable list containing two elements.
static <E> List<E> of(E e1, E e2, E e3) It It returns an immutable list containing three elements.
static <E> List<E> of(E e1, E e2, E e3, E e4) It It returns an immutable list containing four elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5) It It returns an immutable list containing five elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6) It It returns an immutable list containing six elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) It It returns an immutable list containing seven elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) It It returns an immutable list containing eight elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) It It returns an immutable list containing nine elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) It It returns an immutable list containing ten elements.

Java 9 List Factory Method Example

In Java 9, we can write this code in vary simple manner with the help of List.of() factory method.

1. import java.util.List; 
2. public class FactoryMethodsExample { 
3. public static void main(String[] args) { 
4. List<String> list = List.of("Java","JavaFX","Spring","Hibernate","JSP"); 
5. for(String l:list) { 
6. System.out.println(l); 
7. } 
8. } 
9. }

Output:
Java
JavaFX
Spring
Hibernate
JSP

Java 9 Set Interface
Java Set interface provides a Set.of() static factory method which is used to create immutable set. The set instance created by this method has the following characteristcis.
• It is immutable
• No null elements
• It is serializable if all elements are serializable.
• No duplicate elements.
• The iteration order of set elements is unspecified and is subject to change.

Java 9 Set Interface Factory Methods

The following table contains the factory methods for Set interface.

Modifier and Type Method Description
static <E> Set<E> of() It It returns an immutable set containing zero elements.
static <E> Set<E> of(E e1) It It returns an immutable set containing one element.
static <E> Set<E> of(E… elements) It It returns an immutable set containing an arbitrary number of elements.
static <E> Set<E> of(E e1, E e2) It It returns an immutable set containing two elements.
static <E> Set<E> of(E e1, E e2, E e3) It It returns an immutable set containing three elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4) It It returns an immutable set containing four elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5) It It returns an immutable set containing five elements.
static <E> Set<E> It It returns an immutable set containing six elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) It It returns an immutable set containing seven elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) It It returns an immutable set containing eight elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) It It returns an immutable set containing nine elements.
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) It It returns an immutable set containing ten elements.

Java 9 Map Interface Factory Methods

In Java 9, Map includes Map.of() and Map.ofEntries() static factory methods that provide a convenient way to creae immutable maps.
Map created by these methods has the following characteristics.
• It is immutable
• It does not allow null keys and values
• It is serializable if all keys and values are serializable
• It rejects duplicate keys at creation time
• The iteration order of mappings is unspecified and is subject to change.

Java 9 Map Interface Factory Methods

The following table contains the factory methods for Map interface.

Modifier and Type Method Description
static <K,V> Map<K,V> of() It returns an immutable map containing zero mappings.
static <K,V> Map<K,V> of(K k1, V v1) It returns an immutable map containing a single mapping.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2) It returns an immutable map containing two mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3) It returns an immutable map containing three mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) It returns an immutable map containing four mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) It returns an immutable map containing five mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) It returns an immutable map containing six mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) It returns an immutable map containing seven mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) It returns an immutable map containing eight mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) It returns an immutable map containing nine mappings.
static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) It returns an immutable map containing ten mappings.
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>… entries) It returns an immutable map containing keys and values extracted from the given entries.

Java 9 Map Interface Factory Methods Example

1. import java.util.Map; 
2. public class FactoryMethodsExample { 
3. public static void main(String[] args) { 
4. Map<Integer,String> map = Map.of(101,"JavaFX",102,"Hibernate",103,"Spring MVC"); 
5. for(Map.Entry<Integer, String> m : map.entrySet()){ 
6. System.out.println(m.getKey()+" "+m.getValue()); 
7. } 
8. } 
9. }

Output:
102 Hibernate
103 Spring MVC
101 JavaFX

Java 9 Map Interface ofEntries() Method Example

In Java 9, apart from static Map.of() methods, Map interface includes one more static method Map.ofEntries(). This method is used to create a map of Map.Entry instances.
In the following example, we are creating map instance with the help of multiple map.entry instances.

1. import java.util.Map; 

2. public class FactoryMethodsExample { 
3. public static void main(String[] args) { 
4. // Creating Map Entry 
5. Map.Entry<Integer, String> e1 = Map.entry(101, "Java"); 
6. Map.Entry<Integer, String> e2 = Map.entry(102, "Spring"); 
7. // Creating Map using map entries 
8. Map<Integer, String> map = Map.ofEntries(e1,e2); 
9. // Iterating Map 
10. for(Map.Entry<Integer, String> m : map.entrySet()){ 
11. System.out.println(m.getKey()+" "+m.getValue()); 
12. } 
13. } 
14. }

Output:
102 Spring
101 Java

So, this brings us to the end of blog. This Tecklearn ‘Factory Methods in Java 9’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Factory Methods in Java 9"

Leave a Message

Your email address will not be published. Required fields are marked *