- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Which factory methods have added for collections in Java 9?
Factory methods are a special type of static methods that can be used to create unmodifiable instances of collections. It means that we can use these methods to create a list, set, and map of a small number of elements.
List.of()
The List.of() is a static factory method that provides a convenient way to create immutable lists.
Syntax
List.of(elements...)
Example
import java.util.List; public class ListTest { public static void main(String[] args) { List<String> list = List.of("item 1", "item 2", "item 3", "item 4", "item 5"); for(String l : list) { System.out.println(l); } } }
Output
item 1 item 2 item 3 item 4 item 5
Set.of() method
The Set.of() is a static factory method that provides a convenient way to create immutable sets.
Syntax
Set.of(elements...)
Example
import java.util.Set; public class SetTest { public static void main(String[] args) { Set<String> set = Set.of("Item 1", "Item 2", "Item 3", "Item 4", "Item 5"); for(String s : set) { System.out.println(s); } } }
Output
Item 5 Item 1 Item 2 Item 3 Item 4
Map.of() and Map.ofEntries() methods
The Map.of() and Map.ofEntries() are static factory methods that provide a convenient way to create immutable maps.
Syntax
Map.of(k1, v1, k2, v2) Map.ofEntries(entry(k1, v1), entry(k2, v2),...)
Example
import java.util.Map; public class MapTest { public static void main(String[] args) { Map<Integer, String> map = Map.of(101, "Raja", 102, "Adithya", 103, "Jai"); for(Map.Entry<Integer, String> m : map.entrySet()) { System.out.println(m.getKey() + " " + m.getValue()); } } }
Output
103 Jai 102 Adithya 101 Raja
- Related Articles
- What are the conditions for Collection factory methods in Java 9?
- Which attributes have added to @Deprecated annotation in Java 9?
- What are new methods have added to the Arrays class in Java 9?
- What are the new methods added to Process API in Java 9?
- What are new methods added to the String class in Java 9?
- What are the new methods added to an Optional class in Java 9?
- @SafeVarargs annotation for private methods in Java 9?
- How to initialize immutable collections in Java 9?
- Factory method to create Immutable List in Java SE 9
- Factory method to create Immutable Map in Java SE 9
- Factory method to create Immutable Set in Java SE 9
- What are the benefits of immutable collections in Java 9?
- Private Methods in Java 9 Interfaces
- What are the rules for private methods in an interface in Java 9?
- Can interfaces have Static methods in Java?

Advertisements