- 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
What are the benefits of immutable collections in Java 9?
In Java 9, several factory methods have added to Collections API. By using these factory methods, we can create unmodifiable list, set and map collection objects to reduce the number of lines of code. The List.of(), Set.of(), Map.of() and Map.ofEntries() are the static factory methods that provide convenient way of creating immutable collections in Java 9.
Benefits of Immutable Collections
- Less heap space: The space required to store a collection data is very less as compared with the traditional approach in earlier versions of java.
- Faster access to data: As the overhead to store data and wrap into Collections.unmodifiable is reduced, now data access becomes faster. It means that the overall efficiency program is increased.
- Thread safety: Immutable collections are naturally thread-safe. As all threads always get the same view of underlying data.
Syntax
List.of(elements...) Set.of(elements...) Map.of(k1, v1, k2, v2)
Example
import java.util.Set; import java.util.List; import java.util.Map; public class ImmutableCollectionsTest { public static void main(String args[]) { List<String> stringList = List.of("a", "b", "c"); System.out.println("List values: " + stringList); Set<String> stringSet = Set.of("a", "b", "c"); System.out.println("Set values: " + stringSet); Map<String, Integer> stringMap = Map.of("a", 1, "b", 2, "c", 3); System.out.println("Map values: " + stringMap); } }
Output
List values: [a, b, c] Set values: [a, b, c] Map values: {a=1, b=2, c=3}
- Related Articles
- How to initialize immutable collections in Java 9?
- What are the benefits of a module in Java 9?
- What are the uses of generic collections in Java?
- 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 meditation?
- What are the benefits of wheatgrass?
- Which factory methods have added for collections in Java 9?
- Why string objects are immutable in java?
- Primitive Wrapper Classes are Immutable in Java
- What are the features of collections in Information Privacy?
- What are the major benefits of Ayurveda?
- What are the health benefits of Clove?
- What are the health benefits of spinach?

Advertisements