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}

Updated on: 21-Feb-2020

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements