Utilizing Factory Methods for Creating Immutable Collections in Java 9
Introduction:
In this tutorial, we will explore the effective use of factory methods of()
and copyOf()
in Java 9 for the creation of immutable collections. Understanding and leveraging these methods can significantly enhance the robustness and efficiency of your software development projects.
Prerequisites:
To implement the concepts discussed in this tutorial, ensure that you have JDK 9 or above installed on your system.
Code Implementation:
Let's delve into the code to comprehend how we can create immutable collections, specifically lists and sets, using the of()
and copyOf()
factory methods in Java 9 and beyond.
Creating Immutable Lists:
To begin with, let's create an immutable list. In earlier versions of Java, achieving immutability was a bit verbose, requiring the use of Collections.unmodifiableList
. However, with Java 9, the process is streamlined using the of()
static factory method.
javaCopy codeimport java.util.List;
public class ImmutableListExample {
public static void main(String[] args) {
// Before Java 9
List<String> names = new ArrayList<>();
names.add("London");
names.add("Mumbai");
names.add("Delhi");
names.forEach(System.out::println);
// Creating an unmodifiable list
List<String> unmodifiableList = Collections.unmodifiableList(names);
unmodifiableList.forEach(System.out::println);
// unmodifiableList.add("NewYork"); -- This will throw - java.lang.UnsupportedOperationException
// Java 9 and beyond
// Using of() static factory methods for List
List<String> citiesList = List.of("London", "Mumbai", "Delhi");
citiesList.forEach(System.out::println);
// citiesList.add("NewYork"); - This will throw - java.lang.UnsupportedOperationException
}
}
Creating Immutable Sets:
Similarly, we can create immutable sets using the of()
factory method. Here's how:
javaCopy codeimport java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class ImmutableSetExample {
public static void main(String[] args) {
// Creating a set
Set<String> nameSet = new HashSet<>();
nameSet.add("Sachin");
nameSet.add("Raj");
nameSet.add("Aparna");
nameSet.forEach(System.out::println);
// Alternative Way using array
new HashSet<>(Arrays.asList("London", "Mumbai", "Delhi", "Newyork", "Indore")).forEach(System.out::println);
}
}
Conclusion:
Incorporating immutable collections into your Java projects not only ensures data integrity but also simplifies concurrent programming and enhances overall application performance. With the introduction of factory methods of()
and copyOf()
in Java 9, the process of creating immutable collections has become more streamlined and intuitive, offering developers a more efficient way to manage data structures effectively.