How to initialize immutable collections in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 provides factory methods to create immutable lists, sets, and maps. It can be useful to create empty or non-empty collection objects. In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections.unmodifiableList() method.

These factory methods allow us for easy initialization of immutable collections whether they are empty or non-empty.

Initialization of immutable list:

List<Integer> immutableEmptyList = List.of();

In the above, we have initialized an empty, immutable List.

Initialization of immutable set:

Set<Integer> immutableEmptySet = Set.of();

In the above, we have initialized an empty, immutable Set.

Initialization of immutable map:

Map<Integer, Integer> immutableEmptyMap = Map.of();

In the above, we have initialized an empty, immutable Map.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ImmutableCollectionTest {
   public static void main(String args[]) {
      List<String> list8 = new ArrayList<String>();
      list8.add("INDIA");
      list8.add("AUSTRALIA");
      list8.add("ENGLAND");
      list8.add("NEWZEALAND");
      List<String> immutableList8 = Collections.unmodifiableList(list8);
      immutableList8.forEach(System.out::println);
      System.out.println();
      List<String> immutableList = List.of("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND");
      immutableList.forEach(System.out::println);
      System.out.println();
      Set<String> immutableSet = Set.of("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND");
      immutableSet.forEach(System.out::println);
      System.out.println();
      Map<String, String> immutableMap = Map.of("INDIA", "India", "AUSTRALIA", "Australia", "ENGLAND", "England", "NEWZEALAND", "Newzealand");
      immutableMap.forEach((key, value) -> System.out.println(key + " : " + value));
      System.out.println();
   }
}

Output

INDIA
AUSTRALIA
ENGLAND
NEWZEALAND

INDIA
AUSTRALIA
ENGLAND
NEWZEALAND

AUSTRALIA
ENGLAND
NEWZEALAND
INDIA

AUSTRALIA : Australia
ENGLAND : England
NEWZEALAND : Newzealand
INDIA : India
raja
Published on 18-Feb-2020 09:22:29
Advertisements