Home >Java >javaTutorial >How to initialize immutable collection in Java 9?

How to initialize immutable collection in Java 9?

王林
王林forward
2023-08-20 23:37:52815browse

在Java 9中如何初始化不可变集合?

Java 9 provides factory methods to create immutable lists, collections and map. It can be used to create empty or non-empty collection objects. In Java 8 and previous versions, we can use utility methods of collection classes such as unmodifiableXXX to create immutable collection objects. If we need to create an immutable list, we can use the Collections.unmodifiableList() method.

These factory methods allow us to easily initialize immutable collections, whether they are empty or non-empty .

Initialization of immutable list:

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

In the above code, we initialize an empty immutableList .

Initializing an immutable collection:

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

In the above code, we initialize an empty immutableSet .

Initialize immutable map:

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

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.<strong>unmodifiableList</strong>(list8);
      immutableList8.forEach(System.out::println);
      System.out.println();
      List<String> immutableList = <strong>List.of</strong>("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND");
      immutableList.forEach(System.out::println);
      System.out.println();
      Set<String> immutableSet = <strong>Set.of</strong>("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND");
      immutableSet.forEach(System.out::println);
      System.out.println();
      Map<String, String> immutableMap = <strong>Map.of</strong>("INDIA", "India", "AUSTRALIA", "Australia", "ENGLAND", "England", "NEWZEALAND", "Newzealand");
      immutableMap.forEach((key, value) -> System.out.println(key + " : " + value));
      System.out.println();
   }
}

Output

<strong>INDIA
AUSTRALIA
ENGLAND
NEWZEALAND

INDIA
AUSTRALIA
ENGLAND
NEWZEALAND

AUSTRALIA
ENGLAND
NEWZEALAND
INDIA

AUSTRALIA : Australia
ENGLAND : England
NEWZEALAND : Newzealand
INDIA : India
</strong>

The above is the detailed content of How to initialize immutable collection in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete