Skip to main content
Java 9 · Topic 2 of 6

Collection factory methods

Definition​

List.of, Set.of and Map.of (Java 9) create small immutable collections in one line. They do not allow null, and Set.of and Map.of reject duplicates.

Example code​

Immutable collections in one line

import java.util.List;
import java.util.Map;
import java.util.Set;

class Demo {
public static void main(String[] args) {
List<String> languages = List.of("Java", "Kotlin", "Scala");
Set<Integer> primes = Set.of(2, 3, 5);
Map<String, Integer> ages = Map.of("Asha", 30, "Ravi", 28);
Map<String, Integer> many = Map.ofEntries(Map.entry("a", 1), Map.entry("b", 2));

System.out.println(languages);
System.out.println(primes.contains(3));
System.out.println(ages.get("Asha") + " " + many.get("b"));

try {
languages.add("Go");
} catch (UnsupportedOperationException e) {
System.out.println("immutable");
}
try {
List.of("a", null);
} catch (NullPointerException e) {
System.out.println("null is not allowed");
}
}
}

// Output:
// [Java, Kotlin, Scala]
// true
// 30 2
// immutable
// null is not allowed

Finished this page? Track your progress (saved only in your browser).