In Java 9, Collections API added several factory methods. By using these factory methods, we can create unmodifiable list, collection, and mapped collection objects, thus reducing the number of lines of code. In Java 9, List.of(), Set.of(), Map.of() and Map.ofEntries() are provided for convenience Static factory method, used to create immutable collections.
<strong>List.of(elements...) Set.of(elements...) Map.of(k1, v1, k2, v2) </strong>
import java.util.Set; import java.util.List; import java.util.Map; public class ImmutableCollectionsTest { public static void main(String args[]) { <strong>List<String></strong> stringList = <strong>List.of</strong>("a", "b", "c"); System.out.println("List values: " + stringList); <strong>Set<String></strong> stringSet = <strong>Set.of</strong>("a", "b", "c"); System.out.println("Set values: " + stringSet); <strong>Map<String, Integer></strong> stringMap = <strong>Map.of</strong>("a", 1, "b", 2, "c", 3); System.out.println("Map values: " + stringMap); } }
<strong>List values: [a, b, c] Set values: [a, b, c] Map values: {a=1, b=2, c=3}</strong>
The above is the detailed content of What are the benefits of immutable collections in Java 9?. For more information, please follow other related articles on the PHP Chinese website!